I am making a platform game in the Libgdx framework. I want to implement the ability to jump for my character. I use the simply formula:
speed += acceleration * delta_time
r += speed * delta_time
It works well, but only for constant frames per second. The lower FPS is, the lower my character jumps. I have no idea what is the cause of this behavior, the height of jumps should be the same :/
There is a fragment of my code:
delta_time=Gdx.graphics.getDeltaTime();
if(input.getUpArrow()){
if(is_in_air==false){
is_in_air=true;
speed_y=speed_y_0;
}
}
if(is_in_air==true){
speed_y-=acceleration*delta_time;
}
else{
speed_y=0;
}
x+=speed_x*delta_time;
y+=speed_y*delta_time;
And here is an illustration (black dots are character positions):
https://i.stack.imgur.com/VnNIK.jpg
This is perfectly normal behaviour given the very simple and highly inaccurate integrator that you use. It is pretty easy to do the math and show that.
Let’s take a single time span of 1/30 seconds. When the game runs at 30 FPS there would be only one update to
speed_yandy, so after 1/30 s the new positiony'would be:Here
dtis the time delta of 1/30 seconds.When the game runs at 60 FPS, in the same 1/30 seconds there would be two updates happening with twice as shorter time delta,
dt/2:Now compare both updated
ypositions:y + speed_y*dt - a*dt^2y + speed_y*dt - a*(3/4)*dt^2Obviously at 60 FPS the new position of
ywould be higher than that at 30 FPS because the subtracted value is lower.This only affects the vertical motion. The horizontal speed is constant and it doesn’t matter if you update
xonce or twice with twice as short time delta, hence when your character jumps it always travels the same horizontal distance to the place where it hits the ground, no matter what the FPS.To solve this you have to take a closer look at the equation of motion under constant acceleration:
The choice of
t=0is arbitrary since laws of physics are invariant under time shifts, so one may taket=0to be the beginning of the update interval and thent=delta_timewould give the position after the current update. The correct update algorithm as follows:Note that
speed_yshould be updated after the vertical position as per the values found in the equation of motion.