【问题标题】:I want to shoot the bullet in the direction of the character我想朝角色的方向射击
【发布时间】:2017-10-09 11:49:01
【问题描述】:

我想向主玩家的方向发射子弹,在这个类中,子弹朝着玩家的方向:

class bala(pygame.sprite.Sprite):
    def __init__(self, img, posX, posY, velproyectil, xmax, ymax):
        pygame.sprite.Sprite.__init__(self)
        self.Bala = img
        self.Bala = pygame.transform.rotate(self.Bala, 90)
        self.rect = self.Bala.get_rect()
        self.speedx = velproyectil
        self.speedy = velproyectil
        self.rect.top = posY - ymax
        self.rect.left = posX - xmax

    def direccion(self, personaje, personajex, personajey):
        dx, dy = self.rect.x - personajex, self.rect.y - personajey
        dist = hypot(dx, dy)
        dx, dy = dx / dist, dy / dist
        self.rect.x += dx * -self.speedx
        self.rect.y += dy * -self.speedy


    def dibujar(self, superficie):
        superficie.blit(self.Bala, self.rect)

但是当我移动播放器时,子弹不会继续前进,并且控制台显示错误:

"File "Juego_clases (Prueba2).py", line 99, in direccion
   dx, dy = dx / dist, dy / dist
ZeroDivisionError: float division by zero" 

按下空格键时会激活子弹,我希望按下空格键时发射的子弹经过相同的方式。 我想要的是向玩家方向射击子弹并且玩家可以躲避它们。

这是正在发生的事情 (gif):https://1drv.ms/i/s!Amz_9onOWtRI3XfQPC4aq_LhuTnj

【问题讨论】:

  • dist 必须为零。在进行除法之前,您需要一个 if 语句来确保 dist 不为 0。
  • 但子弹不会继续移动。这是一个“gif”,显示发生了什么。 (1drv.ms/i/s!Amz_9onOWtRI3XfQPC4aq_LhuTnj)
  • 在某些时候self.rext.x 必须等于personajex 并且self.rect.y 必须等于personajey(假设我猜到了hypot(dx, dy) 的作用)。这将使dist 等于 0。

标签: python python-2.7 pygame


【解决方案1】:

如果物体和目标在同一位置,则距离(dist)为0。这会导致错误:

ZeroDivisionError:浮点除以零

只有当距离(dist)大于0时才能移动子弹:

class bala(pygame.sprite.Sprite):
    # [...]

    def direccion(self, personaje, personajex, personajey):
        dx, dy = personajex - self.rect.x, personajey - self.rect.y
        dist = hypot(dx, dy)
        if dist > 0:
            dx, dy = dx / dist, dy / dist
            self.rect.x += dx * self.speedx
            self.rect.y += dy * self.speedy

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多