ScalaBoy
ScalaBoy

Reputation: 3392

How to check overlapping of objects?

What is the correct way to check if any of the objects worker overlaps with the objects of other classes (including Worker)? If it overlaps, it should change the trajectory. Is there any built-in function in pygame? Any small example would be appreciated.

all_sprites = pygame.sprite.LayeredUpdates()
workers = pygame.sprite.Group()
machines = pygame.sprite.Group()
fences = pygame.sprite.Group()

# create multiple workers
for pos in ((30,30), (50, 400), (200, 100)):
    Worker("images/workers/worker_1.png", "images/workers/worker_2.png", pos, all_sprites, workers)

# create multiple machines
Crane("images/machines/excavator.png", (780,390), all_sprites, machines)

# create multiple geo-fences
for rect in (pygame.Rect(510,150,75,52), pygame.Rect(450,250,68,40)):
    GeoFence(rect, all_sprites, fences)

Upvotes: 0

Views: 276

Answers (1)

sloth
sloth

Reputation: 101052

Since you already use sprites and groups, it's quite easy to add.

Take a look at pygame.sprite.spritecollide.

I suggest creating a group for all sprites that should change the trajectory, as you said, and then use spritecollide in the sprite's update function to check for a collision:

all_sprites = pygame.sprite.LayeredUpdates()
workers = pygame.sprite.Group()
machines = pygame.sprite.Group()
fences = pygame.sprite.Group()
objects = pygame.sprite.Group()

# create multiple workers
for pos in ((30,30), (50, 400), (200, 100)):
    Worker("images/workers/worker_1.png", "images/workers/worker_2.png", pos, all_sprites, workers, objects)

# create multiple machines
Crane("images/machines/excavator.png", (780,390), all_sprites, machines, objects)

# create multiple geo-fences
for rect in (pygame.Rect(510,150,75,52), pygame.Rect(450,250,68,40)):
    GeoFence(rect, all_sprites, fences, objects)

and in the Worker's update method:

    # spritecollide returns a list of all sprites in the group that collide with
    # the given sprite, but if the sprite is in this very group itself, we have
    # to ignore a collision with itself
    if any(s for s in pygame.sprite.spritecollide(self, objects, False) if s != self):
        self.direction = self.direction * -1

If you want pixel perfect collision (instead of rect based collision detection), you can pass pygame.sprite.collide_mask as a fourth parameter to spritecollide if you make sure your sprites have a mask attribute

Upvotes: 1

Related Questions