1

So was learning how to make a game with pygame in a tutorial and that game needed collision so they created pygame masks object but i did not get why to check the collision between two objects we need to find the distance between there x and y coordinate can someone explain me why we need the x and y coordinates distance between the two objects

Here is the code collision function:

def collide(obj1, obj2):
    offset_x = obj2.x - obj1.x
    offset_y = obj2.y - obj1.y
    return obj1.mask.overlap(obj2.mask, (offset_x, offset_y)) != None # (x, y) it will return if collison else false

Can anyone explain me the logic how the mask system in pygame works and why we need offset_x, offset_y

Rabbid76
  • 202,892
  • 27
  • 131
  • 174
Arkodeep Ray
  • 174
  • 14

1 Answers1

1

A mask is created from an image. The masks are just a grid with Boolean values. One field in the mask corresponds to one pixel in the surface. If it is True, the pixel in the corresponding image belongs to the colored sprite. If False, the pixel in the corresponding image belongs to the background. A pygame.mask.Mask object has no position.
The pygame.mask.Mask.overlap method checks whether the objects overlap when they are placed on the screen. Since the objects will not be placed exactly in the same place, you need to specify the offset. See PyGame collision with masks is not working and Collision between masks in PyGame.

+---------------+
| mask 1   .    |
|         oy    |
|          .    |
|... ox ...+-------------+
|          |    |        |
|          |    |        |
+----------|----+        |
           |             |
           | mask 2      |
           +-------------+

ox is offset_x
oy is offset_y

Minimal example: repl.it/@Rabbid76/PyGame-SurfaceMaskIntersect

See also: Mask


When you use pygame.sprite.Sprite objects, you don't need to compute the offset. You can us pygame.sprite.collide_mask, which computes the offsets from the .rect attrbutes. See How can I made a collision mask? and Pygame mask collision

Minimal example: repl.it/@Rabbid76/PyGame-SpriteMask

See also Sprite mask

Rabbid76
  • 202,892
  • 27
  • 131
  • 174