In physics, Sir Isaac Newton taught us that every object near the Earth's surface accelerates downward due to gravity:
$$F = m \cdot g \implies a = g \approx 9.8\text{ m/s}^2$$
When a dropped ball strikes the floor, it compresses and rebounds. The fraction of speed retained after each collision is called the coefficient of restitution $e$:
$$e = \frac{v_{\text{after}}}{v_{\text{before}}}$$
$e = 0.0$: A lump of clay (splats on the floor with zero bounce).
$e = 0.5$: A tennis ball or basketball.
$e = 0.85$: A super-bouncy rubber ball.
$e = 1.0$: A perfectly elastic collision (the ball bounces back to its original drop height forever!).
Using the Matter.js 2D physics engine, we can simulate realistic Newtonian physics directly in our code:
add_floor() places a solid, fixed floor across the bottom of the screen.
add_ball(x, y, radius, bounciness) drops a dynamic physics ball from coordinates $(x, y)$.
While the simulation runs, you can even click and drag the ball with your mouse to fling it across the screen!
add_floor() add_ball(320, 50, 22, 0.85)
Move the mouse over a dotted box for more information.
Physics Viewport: The physics canvas appears in its own dedicated viewport below the code editor, 640 pixels wide by 400 pixels high. $x = 0$ is the left edge, $x = 640$ is the right edge. $y = 0$ is the top, and $y = 400$ is the bottom.
Bounciness (Restitution): A value between $0.0$ (no bounce) and $1.0$ (elastic bounce). Each successive bounce peak decreases by a factor of $e^2$:
$$h_k = h_0 \cdot e^{2k}$$
Mouse Drag: Try clicking and dragging any ball with your mouse while the physics engine is running!
Now you try. Set bounciness = 0.85 and hit Run. Use your mouse to grab the ball and toss it against the floor!
Type your code here:
See your results here:
The code above has ???? for bounciness. Replace ???? with 0.85 and click Run to watch the ball bounce under gravity in the physics viewport!
1. Click and drag the ball with your mouse to grab and fling it around the viewport!
2. Try changing bounciness to 0.2 for a dead drop (like clay), or 1.0 for perpetual elastic bouncing!
Share your code
Show a friend, family member, or teacher what you've done!