itstwalker
itstwalker

Reputation: 53

Pygame Map Collision Detection

I am making a game where there is a png sprite on a scrolling background, png map. I want to be able to create certain paths that the sprite can move along and walls that they cannot move through. Is it possible to use pygame.mask for this?

Thanks for any advice

Upvotes: 2

Views: 310

Answers (1)

Mahsa Hassankashi
Mahsa Hassankashi

Reputation: 2139

Use pygame.mask.from_surface in order to give your sprites a self.mask attribute.

    self.mask = pygame.mask.from_surface(self.image)
Then use [pygame.sprite.collide_mask][2]:

    pygame.sprite.spritecollide(self.player, self.enemies, False, pygame.sprite.collide_mask)

import pygame as pg


class Player(pg.sprite.Sprite):

    def __init__(self, pos):
        super(Player, self).__init__()
        self.image = pg.Surface((120, 120), pg.SRCALPHA)
        pg.draw.polygon(self.image, (0, 100, 240), [(60, 0), (120, 120), (0, 120)])
        self.rect = self.image.get_rect(center=pos)
        self.mask = pg.mask.from_surface(self.image)


class Wall(pg.sprite.Sprite):

    def __init__(self, pos):
        super(Wall, self).__init__()
        self.image = pg.Surface((120, 120), pg.SRCALPHA)
        pg.draw.circle(self.image, (240, 100, 0), (60, 60), 60)
        self.rect = self.image.get_rect(center=pos)
        self.mask = pg.mask.from_surface(self.image)


class Game:
    def __init__(self):
        self.screen = pg.display.set_mode((640, 480))
        self.player = Player((20, 20))
        self.enemies = pg.sprite.Group(Wall((320, 240)))
        self.all_sprites = pg.sprite.Group(self.player, self.enemies)
        self.done = False
        self.clock = pg.time.Clock()

    def run(self):
        while not self.done:
            self.event_loop()
            self.update()
            self.draw()
            pg.display.flip()
            self.clock.tick(60)

    def event_loop(self):
        for event in pg.event.get():
            if event.type == pg.QUIT:
                self.done = True
            elif event.type == pg.MOUSEMOTION:
                self.player.rect.center = event.pos

    def update(self):
        # Check if the player collides with an wall sprite. The
        # `pygame.sprite.collide_mask` callback uses the `mask`
        # attributes of the sprites for the collision detection.
        if pg.sprite.spritecollide(self.player, self.enemies, False, pg.sprite.collide_mask):
            pg.display.set_caption('collision')
        else:
            pg.display.set_caption('no collision')

    def draw(self):
        self.screen.fill((30, 30, 30))
        self.all_sprites.draw(self.screen)


if __name__ == '__main__':
    pg.init()
    game = Game()
    game.run()
    pg.quit()

Upvotes: 1

Related Questions