У меня есть массив из 16 бильярдных шаров в JS, и я хочу плавно перемещать каждый шар с его направлением и скоростью.
Для этого я установил таймер, вызывающий UpdateThis ()
каждые 42 мс (для 24 кадров в секунду).
Проблема в том, что UpdateThis ()
требует 53 мс в качестве состояний firebug.
Теперь 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;
}
}
}
кажется, что больше всего времени тратится на ball.MoveTo ()
, который выглядит так:
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;
}
}
и onload выглядит как
nx = setInterval(function() { UpdateThis(); }, 42);
Есть ли у кого-нибудь идеи, как это ускорить?
- ОБНОВЛЕНИЕ 2 -
Вы можете скачать папку с файлом HTML здесь (пароль - пароль)