This simulation is a model of a small rectangular “jack” bouncing around within a large box. The jack is affected by gravity; the box is not, but it is attached by a spring to the world 0,0 and shaken back and forth by an external force.

The simulation was generated using Sympy, by constructing the system Lagrangian using 3d transform matrices (restricted to motion in x,y and rotation about z) and using the Euler-Lagrange equations to solve for the equations of motion, which were then integrated alongside a description of the impacts between each corner of the jack and each wall of the box to produce the final output.

Despite its outward simplicity, the same mechanisms which model the jack-in-a-box can be easily adapted to work with a wide variety of more complex systems.

You can view (and run!) the code which generates this visualization here: https://colab.research.google.com/drive/1nygXEIV5B09a25OJv9bd79YfGfY5xMnY?usp=sharing