Search code examples
javascripthtml5-canvasgame-physics

Increase velocity while smooth interpolating move animation with a 60fps game loop


I have a model with x y positions and vx vy velocity.

var model = { x: 0, y: 0, vx: 1, vy: 0 };

I have an update function that is called every 16ms, that updates the position based on velocity.

function update() {
  model.x += model.vx;
  model.y += model.vy;
}

Now I want to speed up this model by multiplying velocity with a boost:

var boost = 10;
function update() {
  model.x += model.vx * boost;
  model.y += model.vy * boost;
}

This causes the model to jump between positions, instead of interpolating and moving smoothly.

How can I increase the velocity and keep the object moving smooth?


Solution

  • The problem here is that you are multiplying the boost with the velocity.

    Look what is actually going on. The value of boost is 10. Now suppose the velocity is 10 pixels/sec, but due to boost, it will be 100 pixels/sec. This is a huge difference. And this is obvious that it will jump.

    You never want do this usually. I guess you would want to add the boost value with the velocity.

    I assume you know the formulae of kinematics you studied in school.

    One of those is,

    v = u + at
    

    See, here also you actually add the acceleration (boost in your case) to the velocity and not multiply it.

    So, your code will be as follows:

    var boost = 10;
    function update() { 
        model.x += model.vx + boost;
        model.y += model.vy + boost; 
    }
    

    Or you can just decrease the value of boost.

    Or you can add acceleration in your model that would increase whenever you want to boost up and will gradually decrease and the velocity will be normal after some time.

    Still, you will end up with the same problem if the velocity (or acceleration) becomes too high.

    If you really want to increase the velocity 10 times, then there's not much you can do.

    Also, if you are using setInterval, I would recommend you to switch to requestAnimationFrame for 60 FPS animation.