I have an array of 16 billiard balls in JS and you want to smoothly move each ball in its direction and speed.
To do this, I set the timer, typing UpdateThis()every 42 ms (for 24 frames per second).
The problem is that it UpdateThis()takes 53 ms as firebug states.
Now UpdateThisiterates over each ball and calls UpdateBall(ball).
I guess the problem lies there.
UpdateBall looks like this:
function UpdateBall(ball)
{
if(ball.direction.x != 0 && ball.direction.y != 0) {
for(var i = 0; i < balls.length; i++) {
}
var ps = VAdd(ball.position, VMul(ball.direction, ball.speed));
if(ps.x < Bx || ps.y < By || ps.x > Bw || ps.y > Bh) {
ball.direction = VMul(ball.direction, -1);
ball.speed *= 1;
ps = VAdd(ball.position, VMul(ball.direction, ball.speed));
}
ball.position = ps;
ball.MoveTo();
ball.speed *= GRK;
if(ball.speed < 0.05) {
ball.speed = 0;
}
}
}
It seems that the most time is spent on ball.MoveTo(), which is as follows:
function()
{
this.image.style.left = this.position.x + "px";
this.image.style.top = this.position.y + "px";
}
- UPDATE -
function UpdateThis() {
for(var i = 0; i < balls.length; i++) {
var cur = balls[i];
UpdateBall(cur);
balls[i] = cur;
}
}
and onload looks like
nx = setInterval(function() { UpdateThis(); }, 42);
Does anyone have any ideas on how to speed this up?
- UPDATE 2 -
HTML ( - )