微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在pygame中让子弹瞄准玩家

如何解决如何在pygame中让子弹瞄准玩家

到目前为止,我游戏中的敌人只会直接向下射击。我希望能够瞄准玩家。这是我的 Enemy 类的射击方法

class Enemy(sprite.Sprite):

    def shoot(self):
        # Origin position,direction,speed
        # Direction of (0,1) means straight down. 0 pixels along the x axis,and +1 pixel along the y axis
        # Speed of (10,10) means that every frame,the object will move 10 px along the x and y axis.
        self.bullets.shoot(self.rect.center,(0,1),(10,10))

self.bullets 是我的 BulletPool 类的一个实例。

class BulletPool(sprite.Group):

    def shoot(self,pos,speed):

        # Selects a bullet from the pool
        default = self.add_bullet() if self.unlimited else None
        bullet = next(self.get_inactive_bullets().__iter__(),default)
        if bullet is None:
            return False

      
        # Sets up bullet movement
        bullet.rect.center = pos
        bullet.start_moving(direction)
        bullet.set_speed(speed)
        
        # Adds bullet to a Group of active bullets
        self.active_bullets.add(bullet)

这是我的子弹课。

class Bullet(sprite.Sprite):

    def update(self):
        self.move()

    def set_speed(self,speed):
        self.speed = Vector2(speed)

    def start_moving(self,direction):
        self.direction = Vector2(direction)
        self.is_moving = True

    def stop_moving(self):
        self.is_moving = False

    def move(self):
        if self.is_moving:
            x_pos = int(self.direction.x*self.speed.x)
            y_pos = int(self.direction.y*self.speed.y)

            self.rect = self.rect.move(x_pos,y_pos)

使用这个,我只能让精灵直线向上 (0,-1)、向下 (0,1)、向左 (-1,0) 或向右 (1,0),以及组合 x 和轴形成 45 度角,(即 (1,1) 向下和向右)。我不知道如何调整某些东西的角度以使其朝向除这些之外的特定方向。我应该改变移动对象的方式吗?我使用相同的方法来移动我的播放器,当它只是从箭头键进行控制时,它工作得很好。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。