Billards & Collisions
Simulation of a ball bouncing inside a circular boundary using event detection.
You can also find this example as a standalone Python file in the GitHub repository.

The physics of this system involves a point mass moving under gravity inside a circular container of radius :math:`l`. When the ball reaches the boundary, it reflects elastically. The reflection is computed by projecting the velocity onto the normal vector at the collision point and reversing that component.
We define the system parameters: gravity :math:`g`, the radius :math:`l` of the circular boundary, and the initial position and velocity of the ball.
The dynamics are modeled using two Integrator blocks: one for position and one for velocity. A Constant block provides the gravitational acceleration acting on the y-component of velocity. The Scope block records the position for visualization.
Collision Detection and Response
The collision is detected using a zero-crossing event. The detection function computes the distance from the origin minus the boundary radius:
MATHDISPLAY0ENDMATH
When this function crosses zero from below (the ball reaches the boundary), the action function is triggered. The elastic reflection is computed as:
MATHDISPLAY1ENDMATH
where MATHINLINE2ENDMATH is the outward normal at the collision point.
Now we assemble the Simulation with all blocks, connections, and events. The gravity acts only on the y-component of velocity (channel 1). Both position components are connected to the scope for recording.
12:43:14 - INFO - LOGGING (log: True) 12:43:14 - INFO - BLOCKS (total: 4, dynamic: 2, static: 2, eventful: 0) 12:43:14 - INFO - GRAPH (nodes: 4, edges: 3, alg. depth: 1, loop depth: 0, runtime: 0.071ms)
12:43:14 - INFO - STARTING -> TRANSIENT (Duration: 7.00s) 12:43:14 - INFO - -------------------- 1% | 0.0s<0.2s | 3180.1 it/s 12:43:14 - INFO - ####---------------- 20% | 0.1s<0.2s | 3504.5 it/s 12:43:14 - INFO - ########------------ 40% | 0.1s<0.3s | 3334.1 it/s 12:43:14 - INFO - ############-------- 60% | 0.2s<0.1s | 3627.6 it/s 12:43:14 - INFO - ################---- 80% | 0.2s<0.0s | 4135.5 it/s 12:43:14 - INFO - #################### 100% | 0.3s<--:-- | 3991.7 it/s 12:43:14 - INFO - FINISHED -> TRANSIENT (total steps: 818, successful: 778, runtime: 254.47 ms)
Let's visualize the results. First, we plot the x and y coordinates over time:
The 2D trajectory shows the ball bouncing inside the circular boundary. We overlay the boundary circle for reference: