Jack-in-the-Box Simulation

PythonNumPySymPySciPyMatplotlibJupyter

Overview

Jack-in-the-Box is a planar rigid-body dynamics simulation built as a final project for Northwestern's ME 314 (Theory of Machines). It models a cross-shaped "jack" freely bouncing inside a "box" that is simultaneously bouncing on a spring-damper and being shaken side-to-side by a sinusoidal force. Everything — the equations of motion, impact detection, and numerical integration — is derived and implemented from scratch, with no physics engine underneath.

System & Degrees of Freedom

The system has 6 DOF total — 3 for the jack (x, y, rotation) and 3 for the box (x, y, rotation). The jack is modeled as four point masses arranged in a cross. The box is a rigid square plate free to translate and rotate in the plane.

q = [x_jack, y_jack, θ_jack, x_box, y_box, θ_box]ᵀ

Physics & Methods

Euler-Lagrange Equations of Motion

The equations of motion are derived symbolically using the Euler-Lagrange method. The Lagrangian L = T − V captures the kinetic and potential energy of both bodies, and generalized forces account for the spring-damper support and sinusoidal shaking applied to the box.

d/dt (∂L/∂q̇ᵢ) − ∂L/∂qᵢ = Qᵢ

External Forces

  • Vertical spring-damper: stabilizes the box around a nominal height, simulating it resting on a bouncy surface.
  • Horizontal sinusoidal shaking: F = A·sin(ωt) drives lateral oscillation, causing the jack to slam against the walls.

Impact Detection & Velocity Updates

Impacts are detected using unilateral constraint functions ϕ — the signed distance between each jack corner and each box wall. When ϕ ≤ 0 and the bodies are approaching, the collision is resolved instantaneously using rigid-body impulse-momentum laws with a coefficient of restitution of 1.0 (fully elastic). This produces sharp, non-smooth velocity jumps at the exact moment of contact — physically realistic and numerically challenging to get right.

q̇⁺ = q̇⁻ + J · M⁻¹ · nq

RK4 Numerical Integration

The simulation runs for 20 seconds using a fixed-step Runge-Kutta 4 integrator. At each timestep the integrator checks all jack-corner / box-wall constraint pairs and applies impulses before continuing the free-flight integration.

Results

  • Non-smooth velocity jumps at impact events are correctly captured — you can see the jack spin and rebound off each wall.
  • Chaotic but physically plausible jack trajectory: small changes in initial conditions produce wildly different long-term behavior.
  • Coupled translation and rotation between both bodies — the box wobbles and tilts as the jack slams into it.