0

I want to shoot the bullet in the direction of the main player, here in this class, the bullet goes in the player's direction:

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)

But when I move the player, the bullets don't continue their way and the console shows me an error:

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

The bullets are activated when the space bar is pressed down, and I want that the bullets that were fired when the bar is pressed, go through the same way. What I want is to shoot the bullets in the player direction and that the player could dodge them.

Here is what is happening (gif): https://1drv.ms/i/s!Amz_9onOWtRI3XfQPC4aq_LhuTnj

3
  • dist must equal zero. Before doing the division, you need an if statement to ensure dist is not 0. Commented May 10, 2017 at 17:32
  • But the bullets do not keep moving. Here is a "gif" that shows what happens. (1drv.ms/i/s!Amz_9onOWtRI3XfQPC4aq_LhuTnj) Commented May 10, 2017 at 17:46
  • At some point self.rext.x must equal personajex and self.rect.y must equal personajey (assuming my guess of what hypot(dx, dy) does). That would make dist equal to 0. Commented May 10, 2017 at 20:00

1 Answer 1

0

If the object and the target are in the same position, the distance (dist) is 0. This causes the error:

ZeroDivisionError: float division by zero

The bullet can only be moved if the distance (dist) is greater than 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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.