Reference: Movement and Numerical Integration

Euler Integration

Simulating movement comes down to numerical integration. Think back to calculus class and remember that velocity is the derivative of position, while position is the integration of velocity. Visually, at a constant velocity, the distance travelled is the area under the curve, or velocity * time.

But this is much more complicated with non-constant velocity. The distance travelled is still the area under the curve, but there is no simple way to compute it. You have to take the integral of velocity over time.

As you should recall, conceptually the integral is like adding up a bunch of thin rectangles to get the area under the curve. The thinner they get, the closer the approximation is. For simple functions, you can use calculus to determine the integral precisely.

However, for something like the velocity of a player moving around, there is no function to describe it; the value changes at (the player's) will. Fortunately, this is a perfect fit for a numerical method, which updates position over time.

Our main loop updates and displays the simulation one frame at a time. Imagine that each of those thin rectangles is the time for a frame, and we assume constant velocity over that (very brief) frame. The change in position then goes back to simply being that velocity * the frame time. In other words, for each frame:

position = position + (velocity * frame_time)

This is the (perhaps familiar) Euler integration. To make it work, you only need to know the velocity at the beginning of the frame and the amount of time since the last frame. We just discussed in in 1-dimension, but it works easily in 2d by integrating x and y separately.

Euler has some serious limitations for real physics simulation (the constant time assumption introduces too much error), but it's a good place to start.