Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>There are a couple problems I see with your code:</p> <p><strong>Assuming fixed timestep</strong> Your display function isn't guaranteed to be called at evenly spaced intervals. Essentially you're giving your cube's velocity in "meters per frame (<code>m/f</code>)" instead of "meters per second (<code>m/s</code>)". (I'm using meters here as a general distance unit)</p> <p>So, some basic math tells me that <code>m/f = m/s * s/f</code>. In other words, you want to scale the amount you move the cube per frame by the actual timestep since the last frame.</p> <p><strong>Velocity problem</strong> The way your code is written, your <code>velo</code> variable actually represents the position, and you update it each frame with the number 0.005 which I think is what you mean to be your acceleration. If you want to have something accelerating due to gravity, you need to store two values, its position and its velocity. Then each frame, you need to update the velocity by adding the acceleration, and the position by adding the velocity.</p> <p>Here's some code that does both of these things</p> <pre><code>int lastTime=0; void display() { int time = glutGet(GLUT_ELAPSED_TIME); // Time since the start of the program if (lastTime&gt;0) { // Don't move anything the first frame int deltaTime = time-lastTime; // millis elapsed since the last frame velo += -0.005*deltaTime; // Gravity accelerates downwards pos += velo*deltaTime; // Position updated by velocity glTranslateF(0.0, pos, 0.0); // Actually position the square in the correct location } lastTime = deltaTime; } </code></pre> <p>Notice how when I update my velocity with the acceleration I scale that by deltaTime, and when I update my position with the velocity I do the same. Again, the unit analysis from before is an easy way to remember this: <code>deltaTime</code> tells you the number of milliseconds elapsed since the last frame, so its units are "s/f". <code>velo</code> should have units "m/s" to make the motion smooth over time. The amount to update the position this frame is m/s * s/f = m/f. Those units make sense, they measure a distance per frame.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload