【问题标题】:Enemy teleporting when colliding with wall [duplicate]与墙壁碰撞时敌人传送[重复]
【发布时间】:2023-01-28 04:55:48
【问题描述】:

我的敌人移动很好,除了与它传送的墙壁碰撞时。 视频:https://imgur.com/a/tuK0yBg

我试图通过删除任何可能影响这一点的代码来简化我的代码,例如僵尸轮换代码等,但我仍然找不到问题。我不知道它为什么要传送。

敌类代码:

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()

【问题讨论】:

    标签: python pygame


    【解决方案1】:

    在我看来,在您的碰撞代码中,您正在正确更新僵尸矩形,以免逐步穿过墙,但我看到 self.position 没有变化。我认为,如果您以与传送行为应该停止的矩形相同的方式更新僵尸的实际位置。

    【讨论】:

    • 谢谢你帮我注意到这一点。得到它的工作!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多