如何加快这个移动算法?在Javascript中

ale*_*lex 5 javascript game-physics


我在JS中有一个16个台球阵列,希望用它的方向和速度顺畅地移动每个球.
为此,我设置了一个定时器,UpdateThis()每隔42ms 调用一次(24 fps).
问题是UpdateThis()需要53毫秒作为萤火虫状态.
现在UpdateThis迭代每一个球和电话UpdateBall(ball).
我认为那里存在问题.
UpdateBall看起来像这样:

function UpdateBall(ball)
{
if(ball.direction.x != 0 && ball.direction.y != 0) {
    //ball moving!
    for(var i = 0; i < balls.length; i++) {
        //CheckCollision(ball, balls[i]); //even without this it takes 53 ms!
    }

    var ps = VAdd(ball.position, VMul(ball.direction, ball.speed)); //Multiply Direction with speed and add to position!
    if(ps.x < Bx || ps.y < By || ps.x > Bw || ps.y > Bh) { //Bounce off the wall!
        ball.direction = VMul(ball.direction, -1); //Invert direction
        ball.speed *= 1;
        ps = VAdd(ball.position, VMul(ball.direction, ball.speed)); //Calc new position!
    }
    ball.position = ps;
    ball.MoveTo(); //See explanation at the bottom.
    ball.speed *= GRK; //Gravity
    if(ball.speed < 0.05) {
        ball.speed = 0;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

似乎花费最多的时间ball.MoveTo()看起来像这样:

function() 
{
     this.image.style.left = this.position.x + "px";
     this.image.style.top = this.position.y + "px"; 
}
Run Code Online (Sandbox Code Playgroud)


- 更新 -

function UpdateThis() {
    for(var i = 0; i < balls.length; i++) {
         var cur = balls[i];
         UpdateBall(cur);
         balls[i] = cur;
    }
  }
Run Code Online (Sandbox Code Playgroud)

和onload看起来像

nx = setInterval(function() { UpdateThis(); }, 42);
Run Code Online (Sandbox Code Playgroud)

有人对如何提高速度有任何想法吗?

- 更新2 -

你可以在这里下载带有HTML文件的文件夹(密码是密码)

Dav*_*vy8 2

将位置更新与绘图分开怎么样?所以有这样的东西(未经测试的代码):

function DrawBall(ball)
{
    ball.MoveTo(); //Take this line out of UpdateBall
}
Run Code Online (Sandbox Code Playgroud)

-

function UpdateThis() {
    for(var i = 0; i < balls.length; i++) {
         var cur = balls[i];
         UpdateBall(cur);
         balls[i] = cur;
    }
}
Run Code Online (Sandbox Code Playgroud)

-

function DrawThis() {
    for(var i = 0; i < balls.length; i++) {
         DrawBall(balls[i]);
    }
    setTimeout(function() { DrawThis(); }, 42);
}
Run Code Online (Sandbox Code Playgroud)

-

nx = setInterval(function() { UpdateThis(); }, 42);
setTimeout(function() { DrawThis(); }, 42);
Run Code Online (Sandbox Code Playgroud)

如果确实是位置移动慢的话,这样逻辑更新还是在42ms,帧率不会快于42ms,但是会跳帧。(我实际上没有尝试过,所以这都是理论上的,你可能需要调整一些东西)