Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 41 ยท Sprites and Collision

Moving Objects and Boundaries

Move objects with Rects and keys in Pygame, then handle the edges of the screen three ways - clamp, wrap around and bounce - and leave a trail to draw with arrow keys.

An object that sits still is a picture; a game starts when things move. This lesson puts together what you know about the loop, input and rectangles to move an object around and, just as important, to decide what happens when it reaches the edge of the screen. There are three classic answers: stop at the edge (clamp), reappear on the other side (wrap) or turn around (bounce). The movement itself, including delta time and vectors, is covered further in the physics chapter; here we focus on edges.

A moving rectangle

The core of nearly every first game:

Python
player = pygame.Rect(375, 500, 50, 30)
SPEED = 300                                   # pixels per second

while running:
    dt = clock.tick(60) / 1000
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    keys = pygame.key.get_pressed()
    dx = (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) * SPEED * dt
    dy = (keys[pygame.K_DOWN] - keys[pygame.K_UP]) * SPEED * dt
    player.x += dx
    player.y += dy

    screen.fill((20, 20, 30))
    pygame.draw.rect(screen, (90, 200, 120), player)
    pygame.display.flip()

Subtracting booleans is a neat trick: True - False is 1 and False - True is -1. This code has one flaw: Rect coordinates are integers, so a movement of 4.7 pixels is truncated each frame and the object drifts slowly or not at all at low speeds. Keep a float position and copy it to the rect:

Python
pos = pygame.Vector2(player.center)
...
pos += direction * SPEED * dt
player.center = pos

Grid movement

For puzzle games, Snake or roguelikes the object moves one tile per key press. Use KEYDOWN events and a tile size:

Python
TILE = 32
if event.type == pygame.KEYDOWN:
    if event.key == pygame.K_LEFT:
        player.x -= TILE
    elif event.key == pygame.K_RIGHT:
        player.x += TILE

Boundaries: three behaviors

1. Clamp: stop at the edge

Python
player.clamp_ip(screen.get_rect())

One line: clamp_ip moves the rect back inside the screen. This is the default choice for the player character. If the playing field is smaller than the window, clamp to a custom rectangle.

2. Wrap: reappear on the other side

Asteroids and Pac-Man tunnels use this:

Python
if player.left > WIDTH:
    player.right = 0
elif player.right < 0:
    player.left = WIDTH

Because x % WIDTH can make a very elegant wrap for a single coordinate, a float position works too: pos.x %= WIDTH.

3. Bounce: reverse the velocity

Balls in Pong, Breakout and screensavers:

Python
if ball.left < 0 or ball.right > WIDTH:
    velocity.x = -velocity.x
if ball.top < 0 or ball.bottom > HEIGHT:
    velocity.y = -velocity.y

After reversing, also push the object back inside the field, otherwise a fast ball can be "inside" the wall for another frame and flip its velocity again, getting stuck.

Try it: three edge behaviors

Three objects fly off the right edge of a 100 pixel field. Compare where each ends up after the same moves.

Python Clamp, wrap and bounce

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 clamped box sticks at x=80 (right edge at 100), the wrapped one reappears from the left, and the bouncing box turns back.

Drawing with arrow keys

A fun first project: leave a trail as you move. Because Pygame never erases what is already on a surface, you can simply stop clearing the screen (or draw on a separate "canvas" surface and blit it each frame):

Python
canvas = pygame.Surface((WIDTH, HEIGHT))
canvas.fill((255, 255, 255))
brush = pygame.Vector2(WIDTH // 2, HEIGHT // 2)

# each frame:
brush += direction * 200 * dt
pygame.draw.circle(canvas, (40, 40, 200), brush, 4)
screen.blit(canvas, (0, 0))
Python Stand-in: a trail on a canvas

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 shape is the path the brush took, and it stays because we never clear the canvas.

Boundaries that are not the screen

The same ideas work for any rectangle:

  • A playfield inside the window: clamp to field_rect.
  • Walls and platforms: use collision detection and then place the object next to the wall.
  • Tile-based worlds: check the tile in the direction of movement before moving.
  • Scrolling levels: clamp the camera and the player to the world rect, which can be much larger than the screen.

Common mistakes

  • Using < where you need <= and getting one pixel of the object outside the screen. clamp_ip avoids the problem.
  • Moving by pixels per frame instead of per second (see The Game Loop).
  • Not nudging a bouncing object back inside, so it flips direction every frame.
  • Moving diagonally faster; normalize the direction (see Keyboard and Mouse Input).
  • Comparing player.x > WIDTH for the right edge: the object's width is ignored. Use player.right.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which single call keeps a player rect inside the screen?

    clamp_ip moves the rect inside another rect without resizing it.
  2. 2. How does wrap-around movement differ from bouncing?

    Wrapping teleports to the opposite edge; bouncing flips the velocity.
  3. 3. Why should you push a bouncing ball back inside the field after reversing its velocity?

    A fast object can still be beyond the wall next frame, which would flip it again and make it stick.
  4. 4. Why do small speeds sometimes produce no movement with a Rect?

    Keep a float position (for example a Vector2) and copy it to the rect.

Summary

  • Move a rect from key state with dt; keep a float position for smooth slow movement.
  • Clamp, wrap and bounce are the three standard edge behaviors.
  • Use rect.right and rect.bottom, not x and y, for the far edges.
  • Not clearing the canvas leaves trails for drawing programs.
  • The same ideas apply to any bounding rectangle, such as a playfield or world.

Next: Sprites and Groups