3

I'm trying to make a tile based game in pygame and I can't quite get my collision function work. So far I have it that when I hit WASD it checks if it is a valid move before actually moving the sprite.

    def move(self, dx=0, dy=0):
        print("TEST" + str(self.collide_with_walls(dx, dy)))
        if not self.collide_with_walls(dx, dy):
            self.x += dx
            self.y += dy

This is my move function that calls my collide function (Figured I would include it just in case)

def collide_with_walls(self, dx=0, dy=0):
        print("Here 1")
        print(self.game.walls)
        for wall in self.game.walls:
            print("2")
            if wall.x == self.x + dx and wall.y == self.y + dy:
                print("Hit wall")
                return True
            print("No hit wall")
        return False

This is my collide function that is constantly returning false. Important to note that it is never printing "2" so it is never getting in the for loop and when I print out 'self.game.walls' it prints "<Group(0 sprites)>

class Wall(pg.sprite.Sprite):
    def __init__(self, game, x, y):
        self.groups = game.all_sprites, game.walls
        pg.sprite.Sprite.__init__(self, self.groups)
        self.game = game
        self.image = pg.Surface((TILESIZE, TILESIZE))
        self.image.fill(BLACK)
        self.rect = self.image.get_rect()
        self.x = x
        self.y = y
        self.rect.x = x * TILESIZE
        self.rect.y = y * TILESIZE

And here lies the Wall function that places the wall where I have a hunch that the problem is but I can't seem to figure it out. Any advice helps :)

Gavin Tynan
  • 103
  • 1
  • 6

1 Answers1

0

I recommend to use pygame.Rect() a and collidepoint() or colliderect for the collision test. For instance:

def collide_with_walls(self, dx=0, dy=0):
        
        new_rect = self.image.get_rect(topleft = (self.x + dx, self.y + dy))
        
        for wall in self.game.walls:
           
            if new_rect.colliderect(wall.rect):  
                print("Hit wall")
                return True
           
        return False
Rabbid76
  • 202,892
  • 27
  • 131
  • 174