Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 41 ยท Sprites and Collision

Collision Response and Walls

React to collisions in Pygame. Block a player at walls by resolving x and y separately, slide along edges, bounce a ball off a paddle by hit position, and find which side was hit.

Detecting a collision only tells you that two things overlap. The game must then do something: stop the player at a wall, bounce a ball, take damage, pick up an item. That reaction is the collision response, and for solid objects it is the part beginners find tricky. This lesson shows the reliable recipe for walls (move one axis at a time), then reactions for paddles and bricks, such as angled bounces and finding out which side was hit.

Solid walls: resolve each axis separately

The common mistake is to move diagonally and then, on overlap, undo the whole move. The player then sticks to walls and cannot slide along them. The robust approach is:

  1. Move horizontally by dx.
  2. If you now overlap a wall, snap back to its edge.
  3. Move vertically by dy.
  4. If you now overlap a wall, snap back to its edge.
Python
def move(self, dx, dy, walls):
    self.rect.x += dx
    for wall in walls:
        if self.rect.colliderect(wall):
            if dx > 0:                     # moving right: hit the wall's left side
                self.rect.right = wall.left
            elif dx < 0:                   # moving left: hit the wall's right side
                self.rect.left = wall.right

    self.rect.y += dy
    for wall in walls:
        if self.rect.colliderect(wall):
            if dy > 0:                     # moving down: landed on top
                self.rect.bottom = wall.top
            elif dy < 0:                   # moving up: bumped the underside
                self.rect.top = wall.bottom

Because each axis is fixed on its own, a player pressing into a wall at an angle slides along it, which feels natural. The direction of movement tells you which side was hit, so no extra geometry is needed.

Try it: slide along a wall

The player pushes diagonally (right and down) against a tall wall. Horizontal motion is blocked, but vertical motion continues.

Python Axis-separated collision

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 player's right edge stops at 100 (the wall's left side), yet y keeps increasing: the player slides down the wall.

Landing on platforms

The same code handles gravity: when the player moves down into a platform and rect.bottom snaps to wall.top, you know the player is on the ground. Set a flag there:

Python
if dy > 0:
    self.rect.bottom = wall.top
    self.velocity_y = 0
    self.on_ground = True

Reset on_ground = False at the start of each move. Jumping is only allowed while on_ground is true; the physics chapter builds on this.

Which side was hit?

Sometimes you have no movement direction (a ball against a brick) and need to know the side. Compare how deeply the rects overlap on each axis. The shallower overlap is the side that was hit:

Python
def hit_side(moving, wall):
    overlap_left = moving.right - wall.left
    overlap_right = wall.right - moving.left
    overlap_top = moving.bottom - wall.top
    overlap_bottom = wall.bottom - moving.top
    smallest = min(overlap_left, overlap_right, overlap_top, overlap_bottom)
    if smallest == overlap_left:   return "left"
    if smallest == overlap_right:  return "right"
    if smallest == overlap_top:    return "top"
    return "bottom"

For a ball hitting a brick, a left or right hit flips velocity.x, and a top or bottom hit flips velocity.y.

Python Find the side of a hit

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.

Bouncing off a paddle

A paddle that always reflects the ball the same way makes Pong boring. Real paddles change the angle depending on where the ball hits: near the center the ball goes straight, near the edges it deflects sharply. Compute the hit offset from -1 (left end) to +1 (right end), turn it into an angle and rebuild the velocity from the speed:

Python
offset = (ball.centerx - paddle.centerx) / (paddle.width / 2)    # -1 .. 1
offset = max(-1, min(1, offset))
angle = offset * 60                                              # up to 60 degrees from vertical
velocity = pygame.Vector2(0, -1).rotate(angle) * speed

Vector2.rotate turns the vector by degrees, so the ball always leaves upward and keeps its speed.

Python Angled paddle 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 speed stays 400 at every hit; only the direction changes. With screen coordinates (y points down), a positive angle sends the ball to the right.

Pushing, damage and pickups

Not every collision is a wall:

  • Pickups: spritecollide(player, coins, True) removes them and you add to the score.
  • Damage: on overlap with an enemy, reduce health and start invincibility frames (a timer during which no further damage is taken), otherwise one touch drains all health in a few frames.
  • Knockback: set the player's velocity to a vector pointing away from the enemy: (player_pos - enemy_pos).normalize() * force.
  • Triggers: invisible rects that start a cutscene or load a level: collision without a physical response.

Separate detecting (who overlaps whom) from reacting (what happens). A clean way is for collision code to post events such as PLAYER_HIT (see Custom Events and Timers) and let other systems respond.

Common mistakes

  • Resolving both axes at once, so the player sticks to walls.
  • Forgetting to snap to the wall's edge, so the player slowly sinks in.
  • Checking the wrong direction (dx > 0 meaning right, not "positive and away from the wall").
  • Flipping a ball's velocity every frame while it overlaps the paddle; push it out first or only react when it moves toward the paddle.
  • Not resetting on_ground each frame.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why resolve horizontal and vertical movement separately for walls?

    Fixing one axis at a time keeps the other axis's motion intact, producing sliding.
  2. 2. The player moves right and overlaps a wall afterwards. What do you do?

    Moving right means the player's right side hit the wall's left side, so snap rect.right to wall.left.
  3. 3. How can you tell which side of a brick a ball hit without knowing its movement?

    The shallowest penetration is the side the ball entered through.
  4. 4. Why vary the bounce angle with the hit position on a paddle?

    Hit position becomes a skill the player can use to aim.
  5. 5. What are invincibility frames?

    They stop one enemy contact from removing all of the player's health in consecutive frames.

Summary

  • Detection says that things overlap; response decides what happens.
  • For solid walls, move on x, resolve, then move on y, resolve; the movement direction gives the hit side.
  • Landing on a platform sets on_ground.
  • Use the smallest overlap to find the hit side of a brick.
  • Vary a paddle bounce by hit position using Vector2.rotate.
  • Add invincibility frames after damage.

Next: Masks and Pixel-Perfect Collision