I'm trying to gradually reduce the velocity of an object, using a "damping" property. After that, I want to move the object's position using the velocity. It looks something like this:
velocity.x *= velocity.damping;
velocity.y *= velocity.damping;
x += velocity.x;
y += velocity.y;
Couldn't be much simpler than that and it works fine, but here is my problem: I'm using a deltaTime variable, that contains the amount of time (in seconds), that the last update of my game-loop took. Applying the velocity is easy enough:
x += velocity.x * deltaTime;
y += velocity.y * deltaTime;
But how can I account for the deltaTime when I multiply the damping property? My idea was, to find the displacement in x or y and multiply the deltaTime to that, like this:
velocity.x += (velocity.x * velocity.damping - velocity.x) * deltaTime;
velocity.y += (velocity.y * velocity.damping - velocity.y) * deltaTime;
Turns out that does not work. I don't really understand why, but I keep getting different results when I test it. If I simply ignore damping or set it to 1.0, everything works, so the problem must be in the last two lines.
velocity.x += (velocity.x * velocity.damping - velocity.x) * deltaTime;
That means you have a constant acceleration, not damping.
velocity.x * (1 - velocity.damping)
is the amount by which you decrement the velocity from the current value in one time unit. It is proportional to the current velocity, so in the next time unit, you would decrement the velocity by a smaller amount using the damping factor. But multiplying with deltaTime
, you subtract the same amount, calculated from the starting value in all of the deltaTime
time units.
Let's suppose a damping factor of 0.9
, so you decrement the velocity by a tenth in each time unit. If you use the linear formula (multiply with deltaTime
), after 10 time units your velocity would become 0, and after 11, it would have switched direction. If you go stepwise, starting from an initial velocity of v_0 = 1
, you'd get
v_1 = v_0*0.9 = 0.9
v_2 = v_1*0.9 = 0.81
v_3 = v_2*0.9 = 0.729
v_4 = v_3*0.9 = 0.6561
etc., a slower decrease of the velocity. If you unfold the formula for v_4
, you get
v_4 = v_3*0.9 = v_2*0.9*0.9 = v_1*0.9*0.9*0.9 = v_0*0.9*0.9*0.9*0.9 = v_0 * 0.9^4
so, generalising, you see that the formula should be
velocity.x *= Math.pow(velocity.damping, deltaTime);
(Assuming Action Script doesn't differ from ECMA Script in what that function is called.)
Similarly for velocity.y
of course.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With