0

バグ シミュレーターの優れた基盤と思われるものはありますが、必要なアニメーションの動きが得られません。

アニメーションで滑らかな動きを作成するためにキャンバスを操作するときの最良のアプローチは何ですか

私は JavaScript が初めてで、いじっているだけなので、コーディング標準を改善するための推奨事項も大歓迎です。

ありがとう

http://jsfiddle.net/UmSss/11/

HTML

<canvas width="578" height="200"  margin="3px" id="targer" style="border: 1px solid black;"></canvas>

ジャバスクリプト

var canvas = document.getElementById('targer');

  function bugObj(x, y, size) { 
        this.x = x;
        this.y = y;
        this.size = size;
        this.update = function(move) {
            var p = Math.floor((Math.random()*3)-1) + this.x;
            var q = Math.floor((Math.random()*3)-1) + this.y;
            if (p > canvas.width) { p = canvas.width };
            if (p < 0)   { p = 0 };
            if (q > canvas.height) { q = canvas.height };
            if (q < 0)   { q = 0 };

            this.x = p;
            this.y = q;
        }
        return this;
    }

    function popBugs(){
        var bug;                
        var ctv = canvas.getContext('2d');  
        ctv.fillStyle = 'black';
        ctv.fillRect(0, 0, canvas.width, canvas.height);
        for(var i = 0; bug = bugs[i]; i++) {                
            ctv.fillStyle = 'yellow';
            ctv.fillRect (bug.x, bug.y, bug.size, bug.size);                
        }

    }

    var bugs = [],
        numberbugs = 100,
        x,y;

    for (var i = 0; i < numberbugs; i++){
        x = Math.random()*canvas.width;
        y = Math.floor(Math.random()*canvas.height);
        bugs.push(new bugObj(x, y, 2)); 
    }

    function loop() {

        /// update each bugs objects
        for(var i = 0;i < bugs.length; i++) bugs[i].update();           

        popBugs();

        requestAnimationFrame(loop);
    }

    loop();

    window.requestAnimationFrame = (function(){
      return  window.requestAnimationFrame       ||
              window.webkitRequestAnimationFrame ||
              window.mozRequestAnimationFrame    ||
              function( callback ){
                window.setTimeout(callback, 1000);
              };
    })();     
4

3 に答える 3

0

現在、バグはフレームごとにランダムな数のピクセルを移動しています。それは彼らに震える効果を与えます。這っているように見せたい場合は、常に前進しながらランダムに回転させる必要があります。そのためには、より複雑なアルゴリズムが必要になります。まず、各フレームの位置を変更する各バグの速度を取得し、時間の経過とともにその速度を変更する必要があります。

また、おそらく探しているものにより近いSteering Behaviorを調査することもできます。

于 2013-07-30T17:37:20.017 に答える