Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 41 ยท Game Physics and Animation

Movement and Delta Time in Pygame

Move objects at a speed that does not depend on frame rate: delta time with Clock.tick, float positions, boundaries, bouncing and a fixed time step loop.

The simplest way to move an object is x += 5 on every frame. It works until the game runs on a faster or slower computer: at 60 frames per second the object travels 300 pixels a second, at 144 it travels 720, and when the frame rate dips it stutters. The fix is to describe speed in units per second and scale each step by how much time has passed. That elapsed time is called delta time (often dt).

This lesson covers delta time, why positions should be floats, how to keep objects inside the screen, how to bounce, and when a fixed time step is better. Pygame code is read-only; the same loops run here as headless simulations so you can compare the results.

Frame-based versus time-based movement

Python
# Frame-based: speed depends on the computer
player.x += 5

# Time-based: 300 pixels per second on every computer
dt = clock.tick(60) / 1000        # milliseconds -> seconds
player.x += 300 * dt

Clock.tick(60) does two things: it sleeps just long enough to cap the loop at 60 frames per second, and it returns the milliseconds since the previous call. Divide by 1000 to get seconds. At 60 fps dt is about 0.0167, so 300 * dt is 5 pixels, the same as before. At 30 fps dt is 0.033 and the step becomes 10 pixels, keeping the speed constant.

Python Frame-based versus delta-time movement

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

With x += 5 the distance after two seconds changes with the frame rate (200 to 1440 pixels). With delta time every row ends at 600.

Why positions must be floats

A pygame.Rect stores integers. If your speed is 90 pixels a second at 60 fps, each frame wants 1.5 pixels, but rect.x += 1.5 truncates, and at slow speeds the object may never move at all. Keep the true position in floats (a Vector2 is ideal) and copy it into the rect only for drawing and collisions:

Python
class Ball:
    def __init__(self):
        self.pos = pygame.Vector2(100, 100)
        self.vel = pygame.Vector2(200, 150)     # pixels per second
        self.rect = pygame.Rect(0, 0, 24, 24)

    def update(self, dt):
        self.pos += self.vel * dt
        self.rect.center = round(self.pos.x), round(self.pos.y)

self.vel * dt is the displacement during this frame: velocity (units per second) times seconds gives units.

Python Integer rects lose small movements

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The rect never moves (0), while the float position correctly reaches 40 pixels after two seconds. In Pygame 2.x the rect truncates the fraction, so tiny steps vanish.

Keeping things on screen

Clamp the position to the window after moving. Rect.clamp_ip does it in one call:

Python
player.rect.clamp_ip(screen.get_rect())

Or check edges by hand, which is more flexible:

Python
if self.pos.x < 0:
    self.pos.x = 0
elif self.pos.x > WIDTH - self.rect.width:
    self.pos.x = WIDTH - self.rect.width

Bouncing

A bounce flips the velocity component that points into the wall. Also push the object back inside, otherwise it can get stuck flipping every frame.

Python
if self.pos.x <= 0 or self.pos.x >= WIDTH - w:
    self.vel.x *= -1
    self.pos.x = max(0, min(self.pos.x, WIDTH - w))

Multiplying by a number slightly under 1 (say -0.9) loses energy on every bounce, which feels more natural.

Python A bouncing ball with delta time

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Controlling the player with speed and acceleration

Instant top speed feels robotic. Smooth movement adds acceleration and friction:

Python
ACCEL = 1500          # pixels per second per second
FRICTION = 8.0
MAX_SPEED = 320

def update(self, dt, direction):          # direction is -1, 0 or +1
    self.vel.x += direction * ACCEL * dt
    self.vel.x -= self.vel.x * min(1, FRICTION * dt)   # drag
    self.vel.x = max(-MAX_SPEED, min(MAX_SPEED, self.vel.x))
    self.pos.x += self.vel.x * dt

Friction proportional to speed settles the player to rest smoothly instead of sliding forever.

When delta time is not enough: fixed time steps

Delta time keeps average speed right, but physics results still differ between frame rates (a jump may go slightly higher at 30 fps than at 144), and a long freeze can make dt huge so objects tunnel through walls. A common remedy is a fixed time step with an accumulator: simulate in constant slices (say 1/120 s), as many as needed to catch up with real time, and draw once per frame.

flowchart TD
  A["frame_time = clock.tick() / 1000"] --> B["accumulator += min(frame_time, 0.25)"]
  B --> C{"accumulator >= STEP?"}
  C -- yes --> D["update(STEP)<br/>accumulator -= STEP"]
  D --> C
  C -- no --> E["draw()"]
  E --> A

Update zero or more times per frame, always with the same step, then draw.

Python Fixed time step with an accumulator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

All three runs perform about 60 updates and end at nearly the same height, so gameplay is identical whatever the display rate. Small differences come from the last partial step carried in the accumulator.

Common mistakes

  • Passing milliseconds: forgetting / 1000 makes everything 1000 times too fast.
  • Calling tick twice per frame: the second call returns almost 0.
  • No cap on dt: dragging the window can pause the game for seconds. Use dt = min(dt, 0.05).
  • Moving the rect directly with fractional speeds, as shown above.
  • Different speeds for diagonals: normalize direction vectors (see Vectors and Angles).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does Clock.tick(60) return?

    tick limits the frame rate and returns the elapsed milliseconds, which you divide by 1000 for delta time.
  2. 2. A sprite should move 240 pixels per second. With dt in seconds, what is the correct per-frame step?

    Speed times time gives distance for this frame.
  3. 3. Why keep a Vector2 for position instead of using rect.x alone?

    Fractions are truncated when assigned to a Rect, so tiny per-frame steps may never accumulate.
  4. 4. What is the purpose of a fixed time step?

    The simulation advances in constant slices, so results do not depend on how fast frames are drawn.

Summary

  • Express speed in units per second and multiply by dt seconds each frame.
  • Clock.tick(fps) caps the rate and returns elapsed milliseconds; clamp huge values.
  • Store positions as floats (Vector2) and copy to the rect for drawing.
  • Clamp or bounce at edges and push the object back inside.
  • Use acceleration and friction for smoother control, and a fixed step with an accumulator for stable physics.

Next: Gravity and Jumping