In part 2 we had a look at the collision detection part of physics engines. In this post we take a look at the collision response part and see what kind of mechanisms it involves.
Velocity is a vector that describes the rate of change in position; the magnitude of the vector is the speed and the direction of the vector is the direction in which the speed is applied.
Force exist in many ways, but generally it is the agent that cause a body to change in motion or make a mass change its velocity. Force has both magnitude and direction and thus it can be expressed as a vector.
Acceleration is change in velocity over time. Acceleration can be defined by isolating a from Newton’s second law:
In the previous velocity definition it is stated that velocity is the displacement over time. If we know the current position, velocity and the force that will be applied on it, we can integrate it to find its position and velocity at some point in the future. The integrator performs numerical integration; that is – it takes a small step into the future and tries to find the next position and velocity an object will have – each time it takes a step, it will use the previous result as the new starting point. It works like this:
- Use initial position, velocity and force
- Step 1 time step into the future and integrate to find the new position and velocity
- Add the position and velocity change to the previous position and velocity
- Go to step 1, using the results obtained in step 3.
This way we can find the position and velocity of any object at any point in the future.
Euler’s method is a simple first-order numerical integrator that we can use to integrate the position of an object. The step-by-step method mentioned above is used in Euler’s method.
Solving an example using Euler’s method of integration:
If we run this code, we will get the following results:
The problem with this is that the result is not correct. Using the equation of motion we should get 500 meters:
But we got 450 using Euler’s method. That is because Euler is inaccurate when velocity over the time step is not constant. Using a smaller time step will get us closer to the real result, but it will always have an error.
There are a lot of alternatives to Euler’s method:
All of them are more accurate than Euler’s method, but they can also be slower (RK4 needs 4 steps at each iteration as an example) and they are more advanced.
Here is an updated overview of the physics engine structure. We just added the Integrator part of the engine.