I went to Stack Overflow and read an algorithm that makes the enemy follow after the player. It worked before, but now it's throwing a zero division error. I understand it's because python's dividing by 0 (meaning the distance between them is 0) however, I don't understand why it throws that error when before, it wasn't throwing it, even if the distance between the two was 0. Can anyone clarify?
import pygame
import math
pygame.init()
width, height = 800, 600
white = (255, 255, 255)
class Enemy(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((40, 50))
self.image.fill(white)
self.rect = self.image.get_rect()
self.rect.x = width / 2
self.rect.y = height/ 2
self.speed = 1
def move_towards_another_object(self):
self.dx = self.rect.x - player.rect.x
self.dy = self.rect.y - player.rect.y
self.dist = math.hypot(self.dx, self.dy)
self.dx = self.dx/self.dist
self.dy = self.dy/self.dist
self.rect.x += self.dx * -self.speed
self.rect.y += self.dy * -self.speed
enemy = Enemy()
class Player(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((50, 40))
self.image.fill(white)
self.rect = self.image.get_rect()
self.rect.x = 0 + self.rect.x
self.rect.y = height - self.rect.height
player = Player()
all_sprites = pygame.sprite.Group()
all_sprites.add(enemy, player)
gameExit = False
while not gameExit:
enemy.move_towards_another_object()
pygame.quit()
quit()
x
andy
are the same number, they're actually one bit apart, sox - y
is not actually 0 but 2e-308. And, whiledx / 0
is aZeroDivsionError
,dx / 2e-308
is not (although the result is probablyfloat.inf
). So, that would explain why two nearly identical runs of the same code, one raises an exception while the other silently runs off to infinity. – abarnert Sep 10 '18 at 21:01