Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PyGame Collision?

How do I find collisions between characters and images within PyGame? I have drawn a player from an image, and have drawn the walls from tiles, so how would I detect these collisions?

like image 551
pixelgeer Avatar asked Feb 16 '12 14:02

pixelgeer


1 Answers

If you use the pygame Rect class to represent the boundaries of your object, you can detect whether two are colliding by using the Rect.colliderect function. For example:

import pygame

a = pygame.Rect((1, 1), (2, 2))
b = pygame.Rect((0, 0), (2, 2))
c = pygame.Rect((0, 0), (1, 1))
a.colliderect(b)
# 1
a.colliderect(c)
# 0
b.colliderect(c)
# 1

a is colliding with b, and b is colliding with c, but a is not colliding with c. Note that rects that share a boundary are not colliding.

Pygame also supports letting you use a Rect as the position for an image when you want to 'blit' it onto the screen.

like image 100
Casey Kuball Avatar answered Oct 05 '22 22:10

Casey Kuball