Game Physics
Learn how real-seeming motion works in games: velocity, gravity, friction, and collision detection — the building blocks of every platformer and arcade game.
In games, we don't just move things by saying "go right." We use velocity — a number that says how fast something moves AND which direction. A positive vx moves right, a negative vx moves left. Same for vy: positive goes down, negative goes up. Each frame, we add the velocity to the position.
Try it!Change vx to -3 and vy to 2. Which direction does the ball go now? Try (0, 3) for straight down!
Gravity isn't a speed — it's an acceleration. That means it changes the velocity over time. Each frame, we add a small gravity value to vy. The ball starts slow, then falls faster and faster — just like in real life! This is how every platformer game works.
Try it!Try changing gravity to 0.1 (moon gravity!) or 1.0 (super heavy). How does it feel different?
When a ball hits the floor, we need to reverse its vy to make it go up. But in real life, bounces lose energy — the ball doesn't bounce back to the same height. We simulate this by multiplying vy by something like -0.8. The minus flips direction, and the 0.8 reduces the speed by 20%.
Try it!Change -0.8 to -1.0 for a perfect bounce (no energy loss). Try -0.5 for a heavy, dead bounce.
Friction makes things slow down over time. Instead of subtracting speed, we multiply vx by a number close to 1, like 0.99. Each frame, the speed drops a tiny bit. Over many frames, it adds up! This is how you make things slide to a stop. Let's add arrow keys so you can push the ball around.
Try it!Change friction from 0.98 to 0.90 — it stops much faster! Try 1.0 for no friction (ice!).
How do you know if two circles are touching? Measure the distance between their centers using dist(). If the distance is less than the sum of their radii, they're overlapping! Here, the ball gets pushed away from a mouse-controlled circle.
Let's bring it all together! An array of balls, each with its own position and velocity. Every frame: apply gravity, move, bounce off walls, and check collisions with the mouse. This is the foundation of how real game physics engines work.
Try it!Try changing the gravity to 0 for a zero-gravity space scene! Or add more balls by changing 8 to 20.
What to try next
- Add a ceiling bounce so balls can't fly off the top of the screen
- Make balls collide with EACH OTHER — check dist() between every pair of balls
- Add a click-to-launch feature: click anywhere to spawn a new ball with velocity toward the mouse
- Build a simple platformer character: arrow keys for left/right, up to jump (only when on the ground!)