Trouble using delta in my movement function

this.up = function () {
this.velocity += this.lift * deltaTime;
};
this.update = function () {
this.velocity += this.gravity * deltaTime;

this.velocity *= 0.9;
this.y += this.velocity;
}

Hi, I have a 2d game on canvas using p5 js thats basically like flappy bird . But Im trying to use deltaTime so the movement is the same regardless of fps.

Does anyone know how I'd apply deltaTime to keep the movement consistent across all fps?

I think it has something to do with the velocity being reduced by 0.9 but Im not sure how to apply delta to that part. Help would be appreciated

New contributor
Buckets is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
• Jan 13 at 1:28

You can apply a time step for constant continuous motion like this:

y += velocity * deltaTime

This only works where the motion is constant. That is, speed is not changing so distance is just how fast for how long.

When you have acceleration and changing speed, you need to use the equations of motion. This will tell you how to calculate distance over time with changing velocity. You can imagine that if you are applying gravity to the velocity, then the speed at the start of the time step is different to the speed at the end of the time step, so assuming constant motion will lead to errors.

You might consider using the equations of motion to calculate both your velocity and position like this:

velocity = old_velocity + gravity * deltaTime 
deltaY = 0.5 * (velocity + old_velocity) * deltaTime 

This is not the only way to apply the equations.

If you do this, even though you are simulating in discrete time steps, the results will converge to actual Newtonian physics.

• With that second part of code, where is the  and  coming from? Also would deltaY be the this.y in my code? Kinda confused Jan 13 at 1:09
• Sorry it was a bit confusing.  and  are the numbers for the equations I used, they are sometimes listed in order from 1 to 5. deltaY is the change in position, so in your code it would look like this.y += deltaY.
– Jay
Jan 13 at 1:28
• Ah okay, I tried using your equation but, should I still keep this.velocity *= 0.9 or does that need to be replaces by the line velocity = old_velocity etc. Im having a hard time getting this to work unfortunately Jan 13 at 2:24
• Not sure what 0.9 represents in your system. If it's for drag, you should think about having acceleration in your system as a = this.lift + this.gravity + 0.9 * this.velocity. One way to set the velocity and position is this.velocity += a * deltatTime and this.y += this.velocity * deltaTime - 0.5 * a * deltaTime * deltatTime.
– Jay
Jan 13 at 2:49
• So that last part you multiply by delta 3 times? Its weird too because when I use that acceleration it says the value of it is infinity, Im not sure Jan 13 at 3:02