我去了Stack Overflow,读了一种算法,该算法使敌人追随玩家。它曾经工作过,但现在却引发了零除错误。我了解这是因为python被0除(意味着它们之间的距离为0),但是,我不明白为什么以前抛出该错误,即使两者之间的距离为0,也没有抛出该错误。有人澄清吗?
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()
答案 0 :(得分:1)
您的enemy
精灵在每次迭代时朝着player
迈出一个单位步长。最终,它与播放器完全重合,并且self.dist
是一个完美的0。您的坐标为 integers ,因此不难得出准确的数学结果。在以前的版本中,坐标是否浮动?可以很容易地解释差异。
答案 1 :(得分:0)
我用这段代码修复了它:
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)
if self.dist == 0:
self.rect.x = self.rect.x
self.rect.y = self.rect.y
else:
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