Does pygame.colliderect() work the same way in both of these situations?

Viewed 66

Say I have 2 hitboxes: hbox1 and hbox2. Does

hbox1.colliderect(hbox2)

and

hbox2.colliderect(hbox1)

always return the same thing?

1 Answers

The method colliderect evaluates, if a pygame.Rect object intersects, with a rectangle. hbox1 and hbox2 are rectangle objects, then the result of hbox1.colliderect(hbox2) is equal to the result of hbox2.colliderect(hbox1). The operation is Commutative.
But note, that the argument to colliderect does not need to be a pygame.Rect object. The argument is allowed to be a tuple, with 4 components (x, y, width, height), too.

If the rectangles (x1, y1, w1, h1) and (x2, y2, w2, h2) are intersection can be evaluated by:

intersect = x1 < x2+w2 and x2 < x1+w1 and y1 < y2+h2 and y2 < y1+h1

It is easy to see that the two rectangles can be swapped and the result will be the same.

Related