Note: It is not a requirement that all material in this tutorial be included in assignment 2. Please see the specs.
In the update/idle function, move the balls over time based on their velocities. Each frame check to see if the balls are intersecting. When an intersection is found, calculate the normal at the point of intersection (we can approximate this to be a direction vector from one ball to the other) and reflect the veolcities of both balls.
Visually debugging collision detection and reaction can be a great way to find errors. Being able to pause time and manually step through simulation frames can be helpful too. Add code to draw normals, velocities and reflection vectors etc. at the point of collision.
You may notice that the collision response does not appear correct, especially if one ball is stationary.
In the lectures 1 dimensional collision reaction has been discussed (see the notes).
For higher dimensions the object velocities are split into two components. One in the direction of the normal and the other in the direction of the tangent. The tangent components do not change while the 1D collision reaction equations are applied to the normal components of the velocities. Finding the velocity components can be calculated using a change of basis or scalar projection. The maths for each method is the same.
M = [Nx, Ny]
[Tx, Ty]
V1i = (M-1 × V1)x
t = (M-1 × V1)y
...
V'1 = M × {V1f, t}
Where V1 is the initial velocity in the standard basis and V'1 is the final velocity after collision in the standard basis.
V1i = V1 · N t = V1 - N × V1i ... V'1 = t + N × V1fThe last equation can be simplified to
V'1 = V1 + N × (V1f - V1i)It should be noted that in this example, the tangent direction and the velocity scalar component is combined in the vector T.
This should provide a convincing bounce.
Print the total kinetic energy and momentum of both balls before and after each collision. A correct simulation will conserve momentum and energy (the totals stay the same) although interaction with static objects such as level bounds may need to be handled separately (for example giving static geometry a virtual momentum).