0

I have seen similar questions asked but they haven't resolved my issue. I have a player class within which there is a function that defines what should happen on collision (push player away from enemy and -1 from player health). In order to define the push away logic I have to reference the Enemy.rect. Enemy is a class which I instance in the game loop). Currently when run I get an error stating that Enemy has no attribute 'rect'. Below I have included the collision function in the player and part of the init of the Enemy to show that it shoul dhave a rect (the enemies are currently moving through manipulation of this rect.) Thank you for any help.

 def collision_check(self):
        self.collision_timer = pygame.time.get_ticks()

        player_enemy_collision = pygame.sprite.spritecollide(self, enemy_group, False)
        collision_tolerance = 4

        if len(enemy_group) > 0:
            if player_enemy_collision and self.collideable:
                for i in player_enemy_collision:
                    if abs(self.rect.top - Enemy.rect.bottom) < collision_tolerance and (self.keys[K_UP]) == 1:
                        self.rect.y = self.player_speed[1] + 20

                    if abs(self.rect.bottom - Enemy.rect.top) < collision_tolerance and (self.keys[K_DOWN]) == 1:
                        self.rect.y = self.player_speed[1] - 20
                    
                    if abs(self.rect.left - Sprite.rect.right) < collision_tolerance and (self.keys[K_LEFT]) == 1:
                        self.rect.y = self.player_speed[1] + 20

                    if abs(self.rect.right - Enemy.rect.left) < collision_tolerance and (self.keys[K_RIGHT]) == 1:
                        self.rect.y = self.player_speed[1] - 20

                    if self.collision_timer - self.collision_timer_start > 500:
                        self.player_damaged()
                        self.collision_timer_start = pygame.time.get_ticks()
                        print('collision', self.health)

class Enemy(pygame.sprite.DirtySprite):
    def __init__(self, pos_x, pos_y, player_x, enemy_type):
        super().__init__()
        self.rect = self.image.get_rect()
        self.rect.center = [pos_x, pos_y]
Shamus
  • 1
  • 1
  • Please post the traceback of the error you are getting – phil Nov 13 '21 at 01:40
  • 1
    From what I can see you're trying to use `rect` as a `class` attribute when it's an `instance` attribute. You need to create an `Enemy` `instance` to access it – phil Nov 13 '21 at 01:44
  • Read about [Class Objects](https://docs.python.org/3/tutorial/classes.html#class-objects). – Rabbid76 Nov 13 '21 at 09:48
  • @phil I am trying to reference the attributes of an instance of the class Enemy. Later in the main game function I create instances and add them to a sprite.Group. I create instances by referencing the Enemy class directly so they all have the same name Enemy. – Shamus Nov 13 '21 at 18:04

0 Answers0