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
distmust equal zero. Before doing the division, you need an if statement to ensuredistis not 0.self.rext.xmust equalpersonajexandself.rect.ymust equalpersonajey(assuming my guess of whathypot(dx, dy)does). That would makedistequal to 0.