The Pygame Rect
already comes with a few collision detection functions that may just do what you need:
pygame.Rect.contains
: test if one rectangle is inside anotherpygame.Rect.collidepoint
: test if a point is inside a rectanglepygame.Rect.colliderect
: test if two rectangles overlappygame.Rect.collidelist
: test if one rectangle in a list intersectspygame.Rect.collidelistall
: test if all rectangles in a list intersectpygame.Rect.collidedict
: test if one rectangle in a dictionary intersectspygame.Rect.collidedictall
: test if all rectangles in a dictionary intersect
Instead of having a detectCollisions
method that takes x1
, y1
, w1
, h1
, x2
, y2
, w2
and h2
, at the sprite initialization you could set its Rect
, move and blit it using that same Rect
as argument to blit, and
then check for collisions with:
sprite1.rect.colliderect(sprite2.rect)
From a A Newbie Guide to pygame:
Rects are your friends.
[...] I have to admit my favorite part of pygame is the lowly Rect class. A rect is simply a rectangle – defined only by the position of its top left corner, its width, and its height. Many pygame functions take rects as arguments, and they also take ‘rectstyles’, a sequence that has the same values as a rect. So if I need a rectangle that defines the area between 10, 20 and 40, 50, I can do any of the following:
rect = pygame.Rect(10, 20, 30, 30) rect = pygame.Rect((10, 20, 30, 30)) rect = pygame.Rect((10, 20), (30, 30)) rect = (10, 20, 30, 30) rect = ((10, 20, 30, 30))
If you use any of the first three versions, however, you get access to Rect’s utility functions. These include functions to move, shrink and inflate rects, find the union of two rects, and a variety of collision-detection functions.
For example, suppose I’d like to get a list of all the sprites that contain a point (x, y) – maybe the player clicked there, or maybe that’s the current location of a bullet. It’s simple if each sprite has a .rect member – I just do:
sprites_clicked = [sprite for sprite in all_my_sprites_list if sprite.rect.collidepoint(x, y)]
Rects have no other relation to surfaces or graphics functions, other than the fact that you can use them as arguments. You can also use them in places that have nothing to do with graphics, but still need to be defined as rectangles. Every project I discover a few new places to use rects where I never thought I’d need them.
So unless you have a specific reason not to rely on Pygame Rect
and its functions, my suggestion would be: don't reinvent the wheel, stick with it.
They might even make use of some internal c code that provides better performance then implementing a pure python approach, although I'm not sure about this specific point.