user2272942
user2272942

Reputation: 63

Using colliderect in Pygame

How do I tell python to detect whether two objects/ images touch each other? For example when an image of pacman touches an image of a ghost?

Upvotes: 1

Views: 15795

Answers (2)

ninMonkey
ninMonkey

Reputation: 7501

I'm assuming you're using Sprites for your pacman and ghost? If so you want one of the sprite collision functions: http://www.pygame.org/docs/ref/sprite.html#pygame.sprite.spritecollide

Otherwise, use the Rect collision Patashu links.

Upvotes: 0

Patashu
Patashu

Reputation: 21773

http://www.pygame.org/docs/ref/rect.html#pygame.Rect.colliderect

colliderect()

test if two rectangles overlap

colliderect(Rect) -> bool

Returns true if any portion of either rectangle overlap (except the top+bottom or left+right edges).

If the only collision detection between sprites is between pac-man and other objects, then just call colliderect on every combination of pacman's collision rectangle and every other collision rectangle.

If every single combination of collisions can be meaningful, then produce a big list of all of them and colliderect each rectangle with each rectangle further along in the list.

Every collision that occurs, you can choose to do something - you could even call both objects, passing the other object that collided, and thereby allowing the logic to be contained within one or both of the objects.

Upvotes: 2

Related Questions