0

my enemy movement is fine except when colliding with walls it teleports. video: https://i.stack.imgur.com/vAqQP.jpg

I have tried to simplify my code by deleting any code that could affect this, e.g. the zombies rotation code etc, however I still can not find the issue. I have no idea why it is teleporting.

Enemy class code:

class Enemy(pygame.sprite.Sprite):
    def __init__(self, position):
        super().__init__(enemy_group, all_sprites_group)
        self.position = pygame.math.Vector2(position) 
        self.zombie_speed = 2 

        self.image = pygame.image.load("zombieAssets/skeleton-idle_0.png").convert_alpha()
        self.image = pygame.transform.rotozoom(self.image, 0, 0.35)
        self.base_zombie_image = self.image

        self.base_zombie_rect = self.base_zombie_image.get_rect(center = position)
        self.rect = self.base_zombie_rect.copy()

        self.velocity = pygame.math.Vector2()

    def hunt_player(self):  
        player_position = player.base_player_rect.center
        distance_to_player = player_position - self.position
        try:
            self.velocity = distance_to_player.normalize() * self.zombie_speed
            self.position += self.velocity

            self.base_zombie_rect.centerx = self.position.x
            self.check_collision("horizontal")

            self.base_zombie_rect.centery = self.position.y
            self.check_collision("vertical")

            self.rect.center = self.base_zombie_rect.center
        except:
            return

    def check_collision(self, direction):
        for sprite in obstacles_group:
            if sprite.rect.colliderect(self.base_zombie_rect):
                if direction == "horizontal":
                    if self.velocity.x > 0:
                        self.base_zombie_rect.right = sprite.rect.left
                    if self.velocity.x < 0:
                        self.base_zombie_rect.left = sprite.rect.right
                
                if direction == "vertical":
                    if self.velocity.y < 0:
                        self.base_zombie_rect.top = sprite.rect.bottom
                    if self.velocity.y > 0:
                        self.base_zombie_rect.bottom = sprite.rect.top
            
    def update(self):
        self.hunt_player()
Rabbid76
  • 202,892
  • 27
  • 131
  • 174
juba1029
  • 47
  • 4

1 Answers1

0

It seems to me that in your collision code you are keeping the zombie rect updated properly so as not to phase through the wall, but I see no changes to self.position. I think that if you updated the zombie's actual position in the same way as the rect that the teleportation behavior should stop.

B Remmelzwaal
  • 1,581
  • 2
  • 4
  • 11