# animating falling object

I'm playing around with OpenGL. I wrote a small program to simulate a falling object. My code looks like the following:

static GLfloat last = glfwGetTime();
GLfloat now = glfwGetTime();
GLfloat delta = now - last;
const GLfloat g = -9.8;

velocity += g * delta;
distance += velocity * delta;


now for some reason the object falls really slowly. However, if I remove the * delta from the last line

distance += velocity;


the simulation appears correct. But if g = acceleration = $m/s^2$ then g * delta = $m/s$ = velocity. Then velocity * delta = $m$, right? Where did I go wrong?

• maybe it's the scale, when the height you are timing is 1000 m then falling is going to seem slow. Mar 23, 2017 at 14:17
• I didn't think about that. I have an 800x800 window and I have the viewport mapped at 1 meter per pixel. I just googled and it takes around 19 seconds to fall from 800 meters. Mar 23, 2017 at 14:30
• You should print out all the values to debug this code. The first bug is that last is only initialized once: it's the time of the first frame, not the time of the previous frame. Mar 23, 2017 at 17:01
• actually, it's initialized every frame. I did debug. Mar 23, 2017 at 18:36

As Dan Hulme points out in a comment, the variable last is not updated each frame. Assuming this code is within a function, it is initialised to the current time once, the first time this function is called. Every time the function is called after that, the static keyword prevents the last variable from being updated. This variable therefore remains unchanged throughout the animation, always set to the initial time.

If this suspected problem is indeed the case, you can correct it by either not using static variables, or by initialising the static variables and then separately updating them in lines that do not contain the static keyword.

In the current code, I can't think of a way that last could already be set to the current time each frame unless there is more code that has not been posted, in which case we will not be able to help you without seeing it.

There are more subtle problems with simply multiplying by delta, which will give a different trajectory for different delta sizes, but they may not be relevant depending on the accuracy that you require. I have focused on what appears to be the most significant problem, as nothing else can be tested until that is either addressed or proved to be not a problem.

GLfloat now = glfwGetTime();
delta = last - now;
last = now;


delta and last should be initialized as 0.0f outside the gameloop.