animating falling object

-1

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?

mikeglaz

Posted 2017-03-23T13:16:51.900

Reputation: 159

maybe it's the scale, when the height you are timing is 1000 m then falling is going to seem slow. – ratchet freak – 2017-03-23T14:17:37.010

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. – mikeglaz – 2017-03-23T14:30:18.810

1You 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. – Dan Hulme – 2017-03-23T17:01:39.963

1actually, it's initialized every frame. I did debug. – mikeglaz – 2017-03-23T18:36:25.493

Answers

0

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.

trichoplax

Posted 2017-03-23T13:16:51.900

Reputation: 3 748

0

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

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

Milo Lu

Posted 2017-03-23T13:16:51.900

Reputation: 111