Until now, whenever the ship of "Stellar Lighthouse" moved it was because we dictated its position: a straight line, an orbit traced with a rotation, an interpolation. In a physics simulation you do not write the trajectory: you write the forces, and the program works out the motion by applying Newton's laws over and over again, in very small time steps. It is the technique that makes a ship coast on its inertia, an object fall along a believable parabola or two containers bounce when they collide. Mathematically it requires nothing we do not already have: states and forces are vectors, collisions are detected with the tests of Module 3 and resolved with dot products, and rotations are integrated with quaternions. What is new is time, and with it a delicate question: how much error is made by advancing in jumps.
The code assumes that all the functions from the previous lessons have been imported (from mini3d import *). Units: meters, seconds, kilograms and newtons.
State of a body and Newton's laws
To simulate a body as a particle (a point with mass; we will deal with its rotation at the end) it is enough to know three things, its state:
| Quantity | Symbol | Type | Unit |
|---|---|---|---|
| Position | \(\mathbf{p}\) | Point | m |
| Velocity | \(\mathbf{v}\) | Vector | m/s |
| Mass | \(m\) | Scalar | kg |
Velocity is the rate of change of position, and acceleration \(\mathbf{a}\), that of velocity:
\[ \frac{d\mathbf{p}}{dt} = \mathbf{v} \qquad\qquad \frac{d\mathbf{v}}{dt} = \mathbf{a} \]
Newton's three laws, written with vectors, say:
- Inertia. Without forces, the velocity does not change: the body follows the line \(\mathbf{p}(t) = \mathbf{p}_0 + t,\mathbf{v}\) from "Vectors in 3D Space".
- Fundamental law. The sum of the forces produces an acceleration inversely proportional to the mass: \[ \mathbf{F} = m,\mathbf{a} \quad\Longrightarrow\quad \mathbf{a} = \frac{1}{m} \sum_i \mathbf{F}_i \]
- Action and reaction. If A pushes B with a force \(\mathbf{F}\), B pushes A with \(-\mathbf{F}\).
The second is a vector equation: three equations, one per component, solved at the same time. And forces add as vectors: it is the parallelogram rule of Module 1. All the work of a simulation comes down to one cycle:
flowchart LR
A["State<br/>p, v"] --> B["Forces<br/>F = sum of F_i"]
B --> C["Acceleration<br/>a = F / m"]
C --> D["Integration<br/>new p, v after dt"]
D --> E["Collisions<br/>detect and correct"]
E --> A
Forces as vectors
Each force is a function that, given the state, returns a vector. The most common ones in a game:
| Force | Formula | Depends on | In "Stellar Lighthouse" |
|---|---|---|---|
| Uniform gravity | \(m,\mathbf{g}\) | Nothing (constant) | Objects near the base of the lighthouse |
| Gravitation | \(-\dfrac{\mu,m}{r^2},\hat{\mathbf{r}}\) | The position | The ship in orbit around the asteroid |
| Thrust | \(E,\hat{\mathbf{d}}\) | The orientation of the engine | The ship's thrusters |
| Linear drag | \(-k,\mathbf{v}\) | The velocity | Braking, stabilization |
| Spring (Hooke) | \(-k,(\ell - \ell_0),\hat{\mathbf{d}}\) | The position | Cables, shock absorbers |
Some remarks:
- Uniform gravity. Near the surface of a celestial body, gravity is practically a constant vector \(\mathbf{g}\). Since the force is proportional to the mass, the acceleration \(\mathbf{F}/m = \mathbf{g}\) is the same for every body. On the surface of our asteroid we will set \(\mathbf{g} = (0, -0.8, 0)\) m/s².
- Gravitation. Far from the surface we have to use the inverse-square law: the force points toward the center \(\mathbf{c}\) of the body and decreases with the square of the distance \(r = \lVert \mathbf{p} - \mathbf{c} \rVert\). The vector \(\hat{\mathbf{r}}\) is the unit direction from the center to the body, and \(\mu = G,M\) groups together the gravitational constant and the mass of the celestial body. For the lighthouse asteroid, with center \((0, -10, 0)\) and radius 10, we will take \(\mu = 80\) m³/s²: on its surface that gives \(80/10^2 = 0.8\) m/s², consistent with the previous value.
- Thrust. An engine pushes along a fixed axis of the object: that direction has to be taken to the world with its orientation matrix. The ship's main engine pushes along its longitudinal axis, \(\mathbf{n}_3 = (0.8, 0, 0.6)\).
- Drag. It opposes the velocity. In a vacuum it does not exist, but almost every space game adds an artificial one: without it, a ship that accelerates would never stop and would be very hard to fly.
- Spring. Hooke's law: a spring of natural length \(\ell_0\) pulls (or pushes) with a force proportional to how much it has been stretched (or compressed), in the direction \(\hat{\mathbf{d}}\) that joins its ends.
import numpy as np
from mini3d import *
np.set_printoptions(suppress=True)
def uniform_gravity(mass, g=(0.0, -0.8, 0.0)):
"""Weight of a body in a constant gravity field g."""
return mass * np.asarray(g, dtype=float)
def gravitation(position, center, mu, mass):
"""Attraction toward `center`: magnitude mu * mass / r^2."""
r = np.asarray(position, dtype=float) - np.asarray(center, dtype=float)
return -mu * mass * r / norm(r) ** 3 # r / |r|^3 = direction / |r|^2
def drag(velocity, k):
"""Linear drag: it opposes the velocity."""
return -k * np.asarray(velocity, dtype=float)
def spring(end, anchor, k, rest_length):
"""Hooke force on the `end` of a spring attached at `anchor`."""
d = np.asarray(end, dtype=float) - np.asarray(anchor, dtype=float)
length = norm(d)
return -k * (length - rest_length) * d / length
ship = np.array([8.0, 3.0, 6.0])
nose = np.array([0.8, 0.0, 0.6]) # n3: the ship's longitudinal axis
asteroid_center, MU, SHIP_MASS = np.array([0.0, -10.0, 0.0]), 80.0, 1000.0
weight = gravitation(ship, asteroid_center, MU, SHIP_MASS)
thrust = 3000.0 * nose
braking = drag([2.0, 0.0, -1.0], 600.0)
total = weight + thrust + braking
print(np.round(weight, 1), round(norm(weight), 1))
print(thrust, braking)
print(np.round(total, 1), np.round(total / SHIP_MASS, 3))
print(spring([10.0, 3.0, 6.0], ship, 40.0, 1.5))[-145.1 -235.7 -108.8] 297.4 [2400. 0. 1800.] [-1200. -0. 600.] [1054.9 -235.7 2291.2] [ 1.055 -0.236 2.291] [-20. -0. -0.]
The ship, with a mass of 1000 kg, is 16.4 m from the center of the asteroid, which pulls on it with 297 N downward and toward the axis of the lighthouse. Its engine pushes with 3000 N forward and the drag, with the example velocity \((2, 0, -1)\), brakes it with \((-1200, 0, 600)\) N. The sum, divided by the mass, is the acceleration: \((1.055, -0.236, 2.291)\) m/s². The last line is an elastic cable with a natural length of 1.5 m that joins the ship to the escort drone, located 2 m to its side: it is stretched by 0.5 m and pulls the drone with \(40 \cdot 0.5 = 20\) N toward the ship.
Numerical integration: explicit Euler
We know the state at one instant and the acceleration at that instant. We want the state a little later, after a time step \(\Delta t\). If the forces were constant there would be an exact formula; in general there is none, and we resort to an approximation: integrating numerically.
The simplest idea is to assume that, during a very short step, the velocity and the acceleration barely change:
\[ \mathbf{p}_{n+1} = \mathbf{p}_n + \mathbf{v}n,\Delta t \qquad\qquad \mathbf{v}{n+1} = \mathbf{v}_n + \mathbf{a}_n,\Delta t \]
This is the explicit Euler method: advancing in a straight line, following the tangent, for the whole step. Geometrically it is the usual parametric line, applied twice: once to the position and once to the velocity. Its flaw is that the real trajectory curves during the step and Euler does not see it: at each step it drifts off a little along the tangent, and the errors accumulate.
In mini3d, an integrator receives the state, a function force(position, velocity) that returns the total force, the mass and the step:
def euler_step(position, velocity, force, mass, dt):
"""Explicit Euler: position and velocity advance with the values from the start of the step."""
acceleration = force(position, velocity) / mass
return position + velocity * dt, velocity + acceleration * dtSemi-implicit Euler and Verlet
A minimal change greatly improves the behavior: update the velocity first and move the position with the new velocity.
\[ \mathbf{v}_{n+1} = \mathbf{v}_n + \mathbf{a}n,\Delta t \qquad\qquad \mathbf{p}{n+1} = \mathbf{p}n + \mathbf{v}{n+1},\Delta t \]
This is the semi-implicit Euler method, also called symplectic Euler. It costs exactly the same—the same operations in a different order—and its error in one step is the same size but, as we will see, it does not always accumulate in the same direction: the energy oscillates very close to its correct value instead of growing unchecked. It is the default integrator of most game engines.
The Verlet method (in its "velocity" variant) goes one step further: it uses the acceleration to curve the trajectory within the step and averages the acceleration at the beginning and at the end.
\[ \mathbf{p}_{n+1} = \mathbf{p}_n + \mathbf{v}_n,\Delta t + \tfrac{1}{2},\mathbf{a}n,\Delta t^2 \qquad\qquad \mathbf{v}{n+1} = \mathbf{v}_n + \tfrac{1}{2}\left(\mathbf{a}n + \mathbf{a}{n+1}\right)\Delta t \]
The first formula is that of uniformly accelerated motion; \(\mathbf{a}_{n+1}\) is the acceleration evaluated at the new position.
def semi_implicit_euler_step(position, velocity, force, mass, dt):
"""Semi-implicit Euler: the velocity first; the position uses the new velocity."""
velocity = velocity + force(position, velocity) / mass * dt
return position + velocity * dt, velocity
def verlet_step(position, velocity, force, mass, dt):
"""Velocity Verlet: position with a quadratic term and average of accelerations."""
a0 = force(position, velocity) / mass
position = position + velocity * dt + 0.5 * a0 * dt * dt
a1 = force(position, velocity + a0 * dt) / mass
return position, velocity + 0.5 * (a0 + a1) * dt
def simulate(step, position, velocity, force, mass, dt, steps):
"""Applies the integrator `step` `steps` times and returns the final state."""
for _ in range(steps):
position, velocity = step(position, velocity, force, mass, dt)
return position, velocity| Explicit Euler | Semi-implicit Euler | Velocity Verlet | |
|---|---|---|---|
| New position with | \(\mathbf{v}_n\) | \(\mathbf{v}_{n+1}\) | \(\mathbf{v}_n\) and \(\mathbf{a}_n\) |
| Force evaluations per step | 1 | 1 | 2 (1 if \(\mathbf{a}_{n+1}\) is reused) |
| Global error | Proportional to \(\Delta t\) | Proportional to \(\Delta t\) | Proportional to \(\Delta t^2\) |
| Energy in orbits and springs | Grows without bound | Oscillates, bounded | Oscillates, bounded and very little |
| Use | Teaching only | Game engines | Particles, cloth, molecular dynamics |
For even greater precision there is the fourth-order Runge-Kutta method (RK4), which evaluates the forces four times per step and has an error proportional to \(\Delta t^4\). It is the preferred one for computing trajectories accurately; in interactive simulations with collisions, a cheap symplectic method usually pays off better.
Free fall: comparison with the exact solution
With uniform gravity there is an analytic solution, that of uniformly accelerated motion:
\[ \mathbf{p}(t) = \mathbf{p}_0 + \mathbf{v}_0,t + \tfrac{1}{2},\mathbf{g},t^2 \qquad\qquad \mathbf{v}(t) = \mathbf{v}_0 + \mathbf{g},t \]
It serves to measure the error of the integrators. From the lighthouse lamp, \((0, 12, 0)\), a 50 kg probe is launched with horizontal velocity \((2, 0, -1)\). After 2 seconds:
\[ \mathbf{p}(2) = (0, 12, 0) + 2,(2, 0, -1) + \tfrac{1}{2},(0, -0.8, 0) \cdot 4 = (4,\ 10.4,\ -2) \]
lamp = np.array([0.0, 12.0, 0.0])
v_probe, PROBE_MASS = np.array([2.0, 0.0, -1.0]), 50.0
probe_weight = lambda p, v: uniform_gravity(PROBE_MASS)
exact = lamp + v_probe * 2.0 + 0.5 * np.array([0.0, -0.8, 0.0]) * 2.0 ** 2
print(exact)
for dt in (0.2, 0.1, 0.05):
finals = [simulate(step, lamp, v_probe, probe_weight, PROBE_MASS, dt, round(2.0 / dt))[0]
for step in (euler_step, semi_implicit_euler_step, verlet_step)]
print(dt, [float(np.round(p[1], 4)) for p in finals])The \(x\) and \(z\) coordinates, with no acceleration, come out exact with all three methods; we only show the final height. Three observations:
- Explicit Euler ends up high (10.48 with \(\Delta t = 0.1\)): at each step it moves the probe with the velocity from the beginning, which is smaller than the real one. The semi-implicit one ends up low by exactly the same amount: it uses the velocity from the end of the step, which is larger. Both errors equal \(\tfrac{1}{2},g,\Delta t,t = 0.5 \cdot 0.8 \cdot 0.1 \cdot 2 = 0.08\) m.
- Halving the step halves the error (0.16, 0.08, 0.04): that is what "error proportional to \(\Delta t\)", or a first-order method, means.
- Verlet is exactly right: its position formula is the exact solution when the acceleration is constant.
The ship's orbit: energy and stability
Free fall is an easy exam. The hard one is an orbit, because it lasts indefinitely and any systematic error ends up showing. We place the ship 20 m from the center of the asteroid, at the point \((20, -10, 0)\), with velocity \((0, 0, -2)\), perpendicular to the radius. In a circular orbit, gravity is exactly the centripetal force needed to curve the trajectory, \(m,v^2/r\):
\[ \frac{\mu,m}{r^2} = \frac{m,v^2}{r} \quad\Longrightarrow\quad v = \sqrt{\frac{\mu}{r}} = \sqrt{\frac{80}{20}} = 2\ \text{m/s} \]
With that speed the orbit must be a perfect circle of radius 20, completed in \(2\pi r / v = 62.8\) s. There is also a quantity that must not change, the mechanical energy, the sum of the kinetic energy and the gravitational potential energy:
\[ E = \tfrac{1}{2},m,\lVert \mathbf{v} \rVert^2 - \frac{\mu,m}{r} = \tfrac{1}{2} \cdot 1000 \cdot 4 - \frac{80 \cdot 1000}{20} = -2000\ \text{J} \]
We simulate three minutes (almost three laps) with \(\Delta t = 0.1\) s and record the minimum and maximum radius, the final radius and how far the energy has deviated:
ship_gravity = lambda p, v: gravitation(p, asteroid_center, MU, SHIP_MASS)
def energy(p, v):
return 0.5 * SHIP_MASS * dot_product(v, v) - MU * SHIP_MASS / distance(p, asteroid_center)
p_orbit, v_orbit = np.array([20.0, -10.0, 0.0]), np.array([0.0, 0.0, -2.0])
e0 = energy(p_orbit, v_orbit)
for step in (euler_step, semi_implicit_euler_step, verlet_step):
p, v, radii, energies = p_orbit, v_orbit, [], []
for _ in range(1800): # 180 s with dt = 0.1
p, v = step(p, v, ship_gravity, SHIP_MASS, 0.1)
radii.append(distance(p, asteroid_center))
energies.append(energy(p, v))
deviation = 100.0 * (np.array(energies) - e0) / abs(e0)
print(f"{step.__name__:25s} {min(radii):7.3f} {max(radii):7.3f} {radii[-1]:7.3f}"
f" {deviation.min():8.4f} {deviation.max():8.4f}")euler_step 20.001 25.194 25.194 0.0200 21.7696 semi_implicit_euler_step 19.901 20.101 20.075 0.0000 0.0100 verlet_step 20.000 20.001 20.000 0.0000 0.0000
| Method | Minimum radius | Maximum radius | Final radius | Energy deviation |
|---|---|---|---|---|
| Explicit Euler | 20.001 | 25.194 | 25.194 | Grows nonstop: it reaches +21.8% |
| Semi-implicit Euler | 19.901 | 20.101 | 20.075 | Oscillates between 0 and +0.01% |
| Verlet | 20.000 | 20.001 | 20.000 | Negligible (less than 0.001%) |
With explicit Euler the ship spirals away: at each step it drifts off a little along the tangent, gains height and with it energy that nobody has given it; in three laps it is 5 m farther out and it will keep moving away. With the semi-implicit method, the orbit is not a perfect circle—it has become a very slightly flattened ellipse, between 19.9 and 20.1 m—but it is closed: the error does not accumulate and the ship will still be there a thousand laps from now. Verlet is practically exact. What is striking is that the two Euler methods do the same arithmetic: only the order of two lines changes.
If we measure the position error against the exact solution after 60 s (the ship has turned \(v,t/r = 6\) rad):
exact = asteroid_center + 20.0 * np.array([np.cos(6.0), 0.0, -np.sin(6.0)])
for dt in (0.2, 0.1, 0.05):
errors = [distance(simulate(step, p_orbit, v_orbit, ship_gravity, SHIP_MASS, dt,
round(60.0 / dt))[0], exact)
for step in (euler_step, semi_implicit_euler_step, verlet_step)]
print(dt, np.round(errors, 4))When the step is halved, the error of the two Euler methods is halved (first order), and that of Verlet is divided by four (second order). With the same step, the semi-implicit method is more than 300 times more accurate than the explicit one in this problem, at no extra cost.
Fixed time step
The time between two frames of a game is not constant: it depends on how long each one takes to draw. Using that variable duration as the \(\Delta t\) of the physics has two problems: the result is no longer reproducible (the same game gives different trajectories on two computers), and a slow frame produces a huge step, with a huge error, which can make an object pass through a wall.
The standard solution is to always simulate with a fixed step and take, in each frame, as many steps as fit in the elapsed time. Whatever is left over is kept in an accumulator for the next frame:
PHYSICS_DT = 0.02 # 50 physics steps per second
accumulator, steps_per_frame = 0.0, []
for duration in (0.016, 0.034, 0.021, 0.050, 0.009): # real times of five frames
accumulator += duration
steps = 0
while accumulator >= PHYSICS_DT:
# this is where we would call: p, v = semi_implicit_euler_step(p, v, force, mass, PHYSICS_DT)
accumulator -= PHYSICS_DT
steps += 1
steps_per_frame.append(steps)
print(steps_per_frame, round(accumulator, 3))The first frame lasts less than one step and does not advance the physics; the second takes two steps (it has accumulated 0.050 s) and the fourth, a very slow one, three. In total 0.130 s have elapsed: six steps (0.120 s) and 0.010 s pending. The physics advances at the same rate as the clock, but always with identical steps.
Collisions: detection
After moving the bodies we have to check whether any of them has collided. We already have the detection from Module 3, on bounding volumes:
| Pair | There is contact if | Contact normal \(\hat{\mathbf{n}}\) | Penetration |
|---|---|---|---|
| Sphere–plane | The signed distance from the center to the plane is less than the radius | The normal of the plane | \(r - \text{distance}\) |
| Sphere–sphere | The distance between centers is less than \(r_1 + r_2\) (spheres_overlap) |
The direction between centers | \(r_1 + r_2 - \text{distance}\) |
Besides the yes or no, the response needs two pieces of geometric data: the contact normal, which is the direction in which the bodies push each other, and the penetration, how much they have overlapped because of advancing in jumps.
Impulse response and the coefficient of restitution
A collision lasts thousandths of a second, far less than a simulation step. We do not model the force during the contact, but its total effect: an instantaneous change of velocity. Let us start with a sphere against a stationary plane (the ground).
We decompose the velocity into the part normal to the plane and the tangent part, as in "Distances and Geometric Projections":
\[ \mathbf{v} = \underbrace{(\mathbf{v} \cdot \hat{\mathbf{n}}),\hat{\mathbf{n}}}{\text{normal}} + \underbrace{\mathbf{v} - (\mathbf{v} \cdot \hat{\mathbf{n}}),\hat{\mathbf{n}}}{\text{tangent}} \]
If there is no friction, the collision does not alter the tangent part. The normal part is reversed and reduced by a factor \(e\), the coefficient of restitution:
\[ \mathbf{v}' = \mathbf{v} - (1 + e),(\mathbf{v} \cdot \hat{\mathbf{n}}),\hat{\mathbf{n}} \]
| \(e\) | Type of collision | The formula becomes | Example |
|---|---|---|---|
| 1 | Elastic: no energy is lost | reflect(v, n) |
An ideal billiard ball |
| Between 0 and 1 | Partially elastic | A mixture of the two | Almost everything |
| 0 | Perfectly inelastic: it does not bounce | slide(v, n) |
A sandbag |
The two functions we defined in Module 3 were, without our knowing it, the two extreme cases of a collision. The formula must only be applied if the body is approaching the plane (\(\mathbf{v} \cdot \hat{\mathbf{n}} < 0\)); if it is already moving away, the velocity is left alone.
Example. A probe descends toward the landing strip, whose plane has normal \(\hat{\mathbf{n}} = \left(\tfrac{1}{3}, \tfrac{2}{3}, \tfrac{2}{3}\right)\), with velocity \(\mathbf{v} = (2, -2, -2)\). Then \(\mathbf{v} \cdot \hat{\mathbf{n}} = \tfrac{2 - 4 - 4}{3} = -2\): it is approaching at 2 m/s. With \(e = 0.5\):
\[ \mathbf{v}' = (2, -2, -2) - 1.5 \cdot (-2) \cdot \left(\tfrac{1}{3}, \tfrac{2}{3}, \tfrac{2}{3}\right) = (2, -2, -2) + (1, 2, 2) = (3, 0, 0) \]
The new normal velocity is \(\mathbf{v}' \cdot \hat{\mathbf{n}} = 1\): half the incoming one and in the opposite direction.
def bounce_on_plane(position, velocity, radius, plane, restitution):
"""Collision of a sphere with a stationary plane. Returns (position, velocity)."""
n = plane[0]
separation = point_plane_distance(plane, position)
if separation >= radius:
return position, velocity # they do not touch
position = position + (radius - separation) * n # penetration correction
v_normal = dot_product(velocity, n)
if v_normal < 0.0: # only if it is approaching
velocity = velocity - (1.0 + restitution) * v_normal * n
return position, velocity
strip = plane_from_point_normal([11.0, 0.0, 3.0], [1.0, 2.0, 2.0])
v_incoming = np.array([2.0, -2.0, -2.0])
for e in (1.0, 0.5, 0.0):
print(e, np.round(bounce_on_plane(np.array([11.0, 0.0, 3.0]), v_incoming, 0.5, strip, e)[1], 4))
print(np.round(reflect(v_incoming, strip[0]), 4), np.round(slide(v_incoming, strip[0]), 4))
ground = plane_from_point_normal([0.0, 0.0, 0.0], [0.0, 1.0, 0.0])
p, v, heights, rising = np.array([3.0, 4.5, 0.0]), np.zeros(3), [], False
for _ in range(3000): # 30 s with dt = 0.01
p, v = semi_implicit_euler_step(p, v, probe_weight, PROBE_MASS, 0.01)
p, v = bounce_on_plane(p, v, 0.5, ground, 0.5)
if rising and v[1] <= 0.0:
heights.append(round(float(p[1]) - 0.5, 2)) # height of the base of the probe
rising = v[1] > 0.0
print(heights[:4])1.0 [3.3333 0.6667 0.6667] 0.5 [3. 0. 0.] 0.0 [ 2.6667 -0.6667 -0.6667] [3.3333 0.6667 0.6667] [ 2.6667 -0.6667 -0.6667] [0.99, 0.24, 0.06, 0.01]
The first three lines confirm the example and the two extreme cases. The second part drops a probe of radius 0.5 from a height of 4 m onto the horizontal esplanade of the lighthouse and records the maximum height after each bounce: approximately 1, 0.25, 0.06... Each bounce rises a quarter as high as the previous one. It has to be so: the velocity after the collision is \(e = 0.5\) times the incoming one, and the height reached by a body thrown upward is proportional to the square of its velocity, \(h = v^2 / (2g)\); therefore \(h' = e^2,h\).
Collision between two spheres and penetration correction
When two moving bodies collide, both change velocity. The third law says how: during the collision they exchange opposite impulses along the contact normal. An impulse is a force multiplied by the time for which it acts, and its effect is a change of momentum (\(m,\mathbf{v}\)). If we call its magnitude \(j\) and let \(\hat{\mathbf{n}}\) be the direction from body 1 to body 2:
\[ \mathbf{v}_1' = \mathbf{v}_1 - \frac{j}{m_1},\hat{\mathbf{n}} \qquad\qquad \mathbf{v}_2' = \mathbf{v}_2 + \frac{j}{m_2},\hat{\mathbf{n}} \]
With these formulas the total momentum is conserved automatically: \(m_1 \mathbf{v}_1' + m_2 \mathbf{v}_2' = m_1 \mathbf{v}_1 + m_2 \mathbf{v}_2\), because the two terms with \(j\) cancel. It remains to find \(j\). The condition is the same as for the plane, applied to the relative velocity along the normal, \(v_n = (\mathbf{v}_2 - \mathbf{v}_1) \cdot \hat{\mathbf{n}}\) (negative if they are approaching): after the collision it must equal \(-e,v_n\). Subtracting the two formulas and taking the dot product with \(\hat{\mathbf{n}}\):
\[ v_n' = v_n + j \left(\frac{1}{m_1} + \frac{1}{m_2}\right) = -e,v_n \quad\Longrightarrow\quad j = \frac{-(1 + e),v_n}{\dfrac{1}{m_1} + \dfrac{1}{m_2}} \]
If \(m_2\) tends to infinity (a stationary body), \(1/m_2 = 0\) and we recover the formula for the plane.
The penetration correction separates the bodies along the normal until they are left just touching, sharing out the displacement in inverse proportion to the masses: the light one moves more.
Example. The escort drone (1000 kg, radius 1) is at \((10, 3, 6)\) and advances with velocity \((3, 0, 0)\) toward a container at rest (3000 kg, radius 2) located at \((11.8, 2.1, 7.8)\). The vector between centers is \((1.8, -0.9, 1.8)\), of length 2.7: less than \(1 + 2 = 3\), so they overlap by 0.3 m. The normal is \(\hat{\mathbf{n}} = \left(\tfrac{2}{3}, -\tfrac{1}{3}, \tfrac{2}{3}\right)\).
- Normal relative velocity: \(v_n = \big((0,0,0) - (3,0,0)\big) \cdot \hat{\mathbf{n}} = -2\). They are approaching.
- Impulse, with \(e = 0.5\): \(j = \dfrac{1.5 \cdot 2}{\tfrac{1}{1000} + \tfrac{1}{3000}} = \dfrac{3}{0.001333} = 2250\) N·s.
- Drone: \(\mathbf{v}_1' = (3, 0, 0) - 2.25,\hat{\mathbf{n}} = (1.5,\ 0.75,\ -1.5)\).
- Container: \(\mathbf{v}_2' = 0.75,\hat{\mathbf{n}} = (0.5,\ -0.25,\ 0.5)\).
def resolve_sphere_collision(p1, v1, m1, r1, p2, v2, m2, r2, restitution):
"""Collision between two moving spheres. Returns the corrected (p1, v1, p2, v2)."""
if not spheres_overlap(p1, r1, p2, r2):
return p1, v1, p2, v2
n = direction_to(p1, p2) # contact normal: from 1 to 2
inv1, inv2 = 1.0 / m1, 1.0 / m2
penetration = r1 + r2 - distance(p1, p2)
p1 = p1 - penetration * inv1 / (inv1 + inv2) * n # separate: the light one moves more
p2 = p2 + penetration * inv2 / (inv1 + inv2) * n
v_n = dot_product(v2 - v1, n)
if v_n < 0.0: # only if they are approaching
j = -(1.0 + restitution) * v_n / (inv1 + inv2)
v1, v2 = v1 - j * inv1 * n, v2 + j * inv2 * n
return p1, v1, p2, v2
drone, v_drone = np.array([10.0, 3.0, 6.0]), np.array([3.0, 0.0, 0.0])
container, v_container = np.array([11.8, 2.1, 7.8]), np.zeros(3)
p1, v1, p2, v2 = resolve_sphere_collision(drone, v_drone, 1000.0, 1.0,
container, v_container, 3000.0, 2.0, 0.5)
n = direction_to(drone, container)
print(np.round(v1, 4), np.round(v2, 4))
print(1000.0 * v1 + 3000.0 * v2, round(dot_product(v2 - v1, n), 4))
print(np.round(p1, 3), np.round(p2, 3), round(distance(p1, p2), 4))
print(0.5 * 1000.0 * 9.0, round(0.5 * 1000.0 * v1 @ v1 + 0.5 * 3000.0 * v2 @ v2, 1))[ 1.5 0.75 -1.5 ] [ 0.5 -0.25 0.5 ] [3000. 0. 0.] 1.0 [9.85 3.075 5.85 ] [11.85 2.075 7.85 ] 3.0 4500.0 3375.0
The second line checks the two laws: the total momentum is still \((3000, 0, 0)\) and the normal relative velocity has gone from \(-2\) to \(+1\). The third, that after the correction the centers are exactly 3 m apart; the drone, three times lighter, has moved back three times as far as the container. The last one shows the kinetic energy before and after: part of it has been lost, converted into deformation and heat. Only with \(e = 1\) would it be conserved.
Rotation: angular velocity, orientation and torque
A rigid body, besides translating, rotates. The complete description of rotational motion is longer than that of translation; here we look at its three basic pieces, which parallel the ones we already know:
| Translation | Rotation |
|---|---|
| Position \(\mathbf{p}\) | Orientation: a unit quaternion \(q\) |
| Velocity \(\mathbf{v}\) | Angular velocity \(\boldsymbol{\omega}\) |
| Force \(\mathbf{F}\) | Torque \(\boldsymbol{\tau} = \mathbf{r} \times \mathbf{F}\) |
| Mass \(m\) | Moment of inertia \(I\) |
| \(\mathbf{F} = m,\mathbf{a}\) | \(\boldsymbol{\tau} = I,\boldsymbol{\alpha}\) |
Angular velocity is a vector
The angular velocity \(\boldsymbol{\omega}\) gathers into a single vector the two pieces of data of the axis-angle representation: its direction is the axis of rotation (with the right-hand rule) and its magnitude, the speed of the rotation in radians per second. A point of the body located at \(\mathbf{r}\) relative to the center of rotation moves with velocity
\[ \mathbf{v} = \boldsymbol{\omega} \times \mathbf{r} \]
perpendicular to the axis and to the radius, and all the greater the farther it is from the axis: the cross product does all the work.
Integrating the orientation
During a step \(\Delta t\), the body rotates through an angle \(\lVert \boldsymbol{\omega} \rVert,\Delta t\) about \(\hat{\boldsymbol{\omega}}\). That small rotation is the quaternion \(\Delta q = \left[\cos\tfrac{\theta}{2},\ \sin\tfrac{\theta}{2},\hat{\boldsymbol{\omega}}\right]\) with \(\theta = \lVert \boldsymbol{\omega} \rVert,\Delta t\), and it is composed with the current orientation on the left (it is applied afterwards): \(q_{n+1} = \Delta q,q_n\). For very small angles, \(\cos\tfrac{\theta}{2} \approx 1\) and \(\sin\tfrac{\theta}{2} \approx \tfrac{\theta}{2}\), so that \(\Delta q \approx \left[1,\ \tfrac{1}{2},\boldsymbol{\omega},\Delta t\right]\) and:
\[ q_{n+1} \approx q_n + \tfrac{1}{2},\boldsymbol{\omega},q_n,\Delta t \qquad\text{that is}\qquad \frac{dq}{dt} = \tfrac{1}{2},\boldsymbol{\omega},q \]
where \(\boldsymbol{\omega},q\) is the quaternion product, with \(\boldsymbol{\omega}\) written as the pure quaternion \([0, \omega_x, \omega_y, \omega_z]\). This is the Euler step for the orientation. As with any sum of quaternions, the result is no longer a unit quaternion and it has to be renormalized at every step.
def integrate_orientation(q, omega, dt):
"""Advances the orientation q by a step dt with angular velocity omega (in the world, rad/s)."""
omega_pure = np.concatenate(([0.0], np.asarray(omega, dtype=float)))
derivative = 0.5 * quaternion_product(omega_pure, q)
return quaternion_normalize(q + derivative * dt)
q_ship = matrix_to_quaternion(np.array([[0.6, 0.0, 0.8], [0.0, 1.0, 0.0], [-0.8, 0.0, 0.6]]))
omega = 0.5 * nose # barrel roll: 0.5 rad/s about the nose
q, q_unnormalized = q_ship, q_ship
for _ in range(100): # 2 s with dt = 0.02
q = integrate_orientation(q, omega, 0.02)
q_unnormalized = q_unnormalized + 0.5 * quaternion_product(
np.concatenate(([0.0], omega)), q_unnormalized) * 0.02
exact = quaternion_product(quaternion_from_axis_angle(nose, 1.0), q_ship)
print(np.round(q, 4), np.round(exact, 4))
print(round(np.degrees(angle_between_orientations(q, exact)), 5), round(norm(q_unnormalized), 5))
print(np.round(cross_product(omega, 4.0 * np.array([0.6, 0.0, -0.8])), 3))After 100 steps, the ship has rotated 1 radian about its nose, and the integrated orientation differs from the exact one by less than a thousandth of a degree. Without normalizing, the norm of the quaternion would have grown to 1.00125: not much, but it keeps growing and would end up deforming the ship. The last line is the velocity of the right wing tip, 4 m from the axis: \(0.5 \cdot 4 = 2\) m/s, upward: in a barrel roll in the positive direction about the nose, the right wing goes up.
Torque and moment of inertia
A force applied away from the center of mass, besides pushing, causes rotation. The quantity that measures this is the torque, or moment of the force:
\[ \boldsymbol{\tau} = \mathbf{r} \times \mathbf{F} \]
where \(\mathbf{r}\) goes from the center of mass to the point of application. The cross product captures the three things that matter: the torque is zero if the force points toward the center or away from it (\(\mathbf{r} \parallel \mathbf{F}\)), it is greatest if the force is perpendicular to the lever arm, and its direction is the axis about which it will make the body rotate.
Just as mass measures the resistance to being accelerated, the moment of inertia \(I\) measures the resistance to being rotated; it depends on the mass and on how it is distributed around the axis (for a solid sphere, \(I = \tfrac{2}{5},m,r^2\)). In an arbitrary body it is a symmetric 3×3 matrix, the inertia tensor, whose eigenvectors are the object's principal axes of rotation: one more use of the diagonalization of Module 1. The angular acceleration is \(\boldsymbol{\alpha} = I^{-1},\boldsymbol{\tau}\), and with it \(\boldsymbol{\omega}\) is updated just as the acceleration updates the velocity.
arm = 4.0 * np.array([0.6, 0.0, -0.8]) # from the center to the right wing tip
maneuver_force = 500.0 * nose # maneuvering thruster, pushing forward
torque = cross_product(arm, maneuver_force)
inertia = 0.4 * SHIP_MASS * 4.0 ** 2 # solid sphere of radius 4
print(torque + 0.0, inertia, np.round(torque / inertia, 4) + 0.0)A 500 N thruster at the right wing tip, pushing forward, produces a torque of 2000 N·m about the \(-Y\) axis: the ship yaws to its left, with an angular acceleration of 0.31 rad/s² if we approximate its inertia by that of a sphere of radius 4. The same force applied at the center would not make it rotate.
Common Mistakes and Tips
- Using explicit Euler "because it is the simplest". The semi-implicit method is just as easy and it is stable. Check the order: first the velocity, then the position with the new velocity.
- Using the frame time as \(\Delta t\). Non-reproducible results and numerical explosions in slow frames. Fixed step and accumulator.
- Very stiff springs with large steps. If \(k\) is large, the spring goes through several oscillations per step and the simulation "blows up". You have to reduce \(\Delta t\) (or the stiffness).
- Adding accelerations to forces. Uniform gravity is an acceleration; to add it to other forces it has to be multiplied by the mass.
- Applying the impulse when the bodies are already separating. If the check \(v_n < 0\) is omitted, two overlapping bodies that are moving apart are pulled back together and stay stuck.
- Forgetting the penetration correction. With gravity acting, a body resting on the ground sinks a little at every step.
- Fast objects passing through thin obstacles (tunneling). If in one step the object advances more than the thickness of the obstacle, it never gets to overlap it. The fix is smaller steps or casting a ray along the displacement (
ray_plane,ray_sphere). - Not renormalizing the orientation quaternion after each step.
- Getting the order wrong in \(\mathbf{r} \times \mathbf{F}\). The cross product is anticommutative: the other way around, the torque comes out with the opposite sign and the object rotates the other way.
- Tip. Keep an eye on a quantity that should be conserved (the energy, the momentum). If it grows by itself, there is a bug in the integrator or in the collision response.
Exercises
Exercise 1. The probe of the example leaves the lamp, \((0, 12, 0)\), with velocity \((2, 0, -1)\) and \(\mathbf{g} = (0, -0.8, 0)\). Compute by hand its state after two steps of \(\Delta t = 0.5\) s with explicit Euler and with semi-implicit Euler, and compare them with the exact solution at \(t = 1\).
Exercise 2. Two identical containers, of 2000 kg and radius 1, collide head-on: the first is at the origin and advances with velocity \((4, 0, 0)\); the second is at rest at \((1.8, 0, 0)\).
a) Compute the velocities after the collision if it is perfectly elastic (\(e = 1\)). b) And if it is perfectly inelastic (\(e = 0\))? What fraction of the kinetic energy is lost? c) Where do the centers end up after the penetration correction?
Exercise 3. The ship is in the circular orbit of the example, at \((20, -10, 0)\), and brakes until it is left with velocity \((0, 0, -1.5)\). With Verlet and \(\Delta t = 0.05\):
a) Does it end up colliding with the asteroid (radius 10)? If so, at what instant and at what speed? b) Repeat with velocity \((0, 0, -1.8)\). What is the minimum distance to the center?
Solutions
Solution 1. The acceleration is constant, \(\mathbf{a} = (0, -0.8, 0)\), and \(\mathbf{a},\Delta t = (0, -0.4, 0)\).
Explicit Euler (the position uses the old velocity):
- Step 1: \(\mathbf{p} = (0, 12, 0) + 0.5,(2, 0, -1) = (1, 12, -0.5)\); \(\mathbf{v} = (2, -0.4, -1)\).
- Step 2: \(\mathbf{p} = (1, 12, -0.5) + 0.5,(2, -0.4, -1) = (2, 11.8, -1)\); \(\mathbf{v} = (2, -0.8, -1)\).
Semi-implicit Euler (the velocity first):
- Step 1: \(\mathbf{v} = (2, -0.4, -1)\); \(\mathbf{p} = (0, 12, 0) + 0.5,(2, -0.4, -1) = (1, 11.8, -0.5)\).
- Step 2: \(\mathbf{v} = (2, -0.8, -1)\); \(\mathbf{p} = (1, 11.8, -0.5) + 0.5,(2, -0.8, -1) = (2, 11.4, -1)\).
Exact: \(\mathbf{p}(1) = (0, 12, 0) + (2, 0, -1) + \tfrac{1}{2}(0, -0.8, 0) = (2, 11.6, -1)\). The final velocities coincide and are exact; in height, explicit Euler ends up 0.2 m above and the semi-implicit method 0.2 m below, that is, \(\tfrac{1}{2},g,\Delta t,t = 0.5 \cdot 0.8 \cdot 0.5 \cdot 1\).
Solution 2. The normal is \(\hat{\mathbf{n}} = (1, 0, 0)\) and \(v_n = (0 - 4) = -4\). With equal masses, \(\tfrac{1}{m_1} + \tfrac{1}{m_2} = \tfrac{2}{m}\) and \(j = (1 + e) \cdot 4 \cdot \tfrac{m}{2} = 2,(1 + e),m\); each velocity changes by \(j/m = 2,(1 + e)\).
a) \(e = 1\): a change of 4 m/s. \(\mathbf{v}_1' = (0, 0, 0)\) and \(\mathbf{v}_2' = (4, 0, 0)\): they swap velocities, like billiard balls.
b) \(e = 0\): a change of 2 m/s. \(\mathbf{v}_1' = \mathbf{v}_2' = (2, 0, 0)\): they carry on together. Energy before: \(\tfrac{1}{2} \cdot 2000 \cdot 16 = 16{,}000\) J; after: \(2 \cdot \tfrac{1}{2} \cdot 2000 \cdot 4 = 8000\) J. Half is lost.
c) Penetration: \(2 - 1.8 = 0.2\). With equal masses it is shared equally: the centers end up at \((-0.1, 0, 0)\) and \((1.9, 0, 0)\), 2 m apart.
Solution 3.
print([np.round(simulate(step, lamp, v_probe, probe_weight, PROBE_MASS, 0.5, 2), 4).tolist()
for step in (euler_step, semi_implicit_euler_step)])
a, b = np.zeros(3), np.array([1.8, 0.0, 0.0])
for e in (1.0, 0.0):
p1, v1, p2, v2 = resolve_sphere_collision(a, np.array([4.0, 0.0, 0.0]), 2000.0, 1.0,
b, np.zeros(3), 2000.0, 1.0, e)
print(e, v1 + 0.0, v2, p1 + 0.0, p2, 1000.0 * (v1 @ v1 + v2 @ v2))
for speed in (1.5, 1.8):
p, v, r_min = p_orbit, np.array([0.0, 0.0, -speed]), 20.0
for i in range(1, 4001): # up to 200 s
p, v = verlet_step(p, v, ship_gravity, SHIP_MASS, 0.05)
r_min = min(r_min, distance(p, asteroid_center))
if r_min <= 10.0:
break
print(speed, round(i * 0.05, 2), round(r_min, 3), round(norm(v), 3))[[[2.0, 11.8, -1.0], [2.0, -0.8, -1.0]], [[2.0, 11.4, -1.0], [2.0, -0.8, -1.0]]] 1.0 [0. 0. 0.] [4. 0. 0.] [-0.1 0. 0. ] [1.9 0. 0. ] 16000.0 0.0 [2. 0. 0.] [2. 0. 0.] [-0.1 0. 0. ] [1.9 0. 0. ] 8000.0 1.5 15.15 9.955 3.213 1.8 200.0 13.614 1.886
a) At 1.5 m/s the ship no longer has enough speed to maintain the orbit: it falls toward the asteroid and reaches its surface (radius 10) after 15.15 s, at 3.21 m/s: more than twice its initial speed, because it has converted potential energy into kinetic energy.
b) At 1.8 m/s the circle is not maintained either, but the resulting orbit is an ellipse that never touches the asteroid: in the 200 s simulated, the minimum distance to the center is 13.61 m, 3.6 m from the surface. Braking a little lowers the opposite point of the orbit; braking too much sinks it below the ground.
Conclusion
Simulating means repeating a cycle: add up the forces as vectors, divide by the mass to get the acceleration (\(\mathbf{F} = m,\mathbf{a}\)), integrate one time step and resolve the collisions. The integrator decides the quality of the result: explicit Euler accumulates error and makes orbits gain energy; semi-implicit Euler, with the same operations in a different order, keeps it bounded; Verlet adds one order of accuracy. The step must be fixed. Collisions are detected with the overlap tests of Module 3 and resolved with an impulse along the contact normal, governed by the coefficient of restitution—reflect and slide are its two extremes—and with a penetration correction. Rotation follows the same scheme with a different cast: angular velocity, orientation quaternion (\(\dot{q} = \tfrac{1}{2},\boldsymbol{\omega},q\)), torque \(\mathbf{r} \times \mathbf{F}\) and moment of inertia. mini3d gains uniform_gravity, gravitation, drag, spring, euler_step, semi_implicit_euler_step, verlet_step, simulate, bounce_on_plane, resolve_sphere_collision and integrate_orientation.
In this lesson the ship's orientation has ended up described by a quaternion that changes with time. That same object—a position and a quaternion for each instant—is exactly what a virtual reality headset needs in order to know where its user is looking. In the next lesson, "Virtual and Augmented Reality", we will see how the pose of a head is turned into two images, one per eye, and how the opposite problem is solved: deducing from a real image where the camera is, so that virtual objects can be drawn on top of the world.
