Exerpad
🔥 1
10 XP
Lesson · Chapter: Gravity+10 XP for reading

Speed That Changes

The bouncing dot moved the same amount every frame. Real falling things don't. Drop something and it starts slow, then goes faster and faster.

Here is the whole idea:

Don't change the position. Change the speed — and let the speed change the position.

Two lines, in this order:

python
state["vy"] = state["vy"] + 1 # gravity pulls: speed grows
state["y"] = state["y"] + state["vy"] # then move by that speed
Output
Press Run to see the output.

vy is "velocity in y" — how far it moves this frame. Gravity doesn't move the dot. Gravity makes the dot fall faster, and falling faster is what moves it.

Watch the numbers

Start at y = 0 with vy = 0:

framevyy
111
223
336
4410

Look at the y column: 1, 3, 6, 10. The gaps get bigger every frame. That's acceleration, and you got it from two lines of arithmetic.

Order matters — pick one and stick to it

Swap those two lines and the dot moves using last frame's speed. It still falls, and it still looks fine; everything just happens one frame later.

Both orders are used in real games. What causes bugs is mixing them — a character updated one way and a falling rock the other will drift apart over time, and that is a horrible thing to debug.

This chapter changes the speed first, then moves. Chapter 11 does it the other way round, because that game was written first. Neither is wrong. Just know which one you are doing.

Bouncing with speed

To bounce a falling ball off the floor, flip the speed instead of a direction:

python
if state["y"] >= HEIGHT - 1:
state["vy"] = -state["vy"]
Output
Press Run to see the output.

Flip it exactly and the ball bounces back to where it started, forever. Take a bit off — -state["vy"] * 3 // 4 — and each bounce is smaller, which is what a real ball does.