The result of ene_x // dist
and ene_y // dist
is always 0. To calculate the movement, you must use the /
(division) operator rather than the //
(floor division) operator
ene_x, ene_y = ene_x // dist, ene_y // dist
ene_x, ene_y = ene_x / dist, ene_y / dist
Since pygame.Rect
is supposed to represent an area on the screen, a pygame.Rect
object can only store integral data.
The coordinates for Rect objects are all integers. [...]
The fraction part of the movement gets lost when the position of the object incremented:
self.enemy_rect.x += ene_x * self.ENEMY_ACCELERATION
self.enemy_rect.y += ene_y * self.ENEMY_ACCELERATION
If you want to store object positions with floating point accuracy, you have to store the location of the object in separate variables respectively attributes and to synchronize the pygame.Rect
object. round
the coordinates and assign it to the location (e.g. .topleft
) of the rectangle:
x, y = # floating point coordinates
rect.topleft = round(x), round(y)
Add floating point coordinates to the Enemy
class:
class Enemy:
def __init__(self, enemy_y, enemy_x):
# [...]
self.enemy_rect = pygame.Rect(enemy_x, enemy_y, self.ENEMY_HEIGHT, self.ENEMY_WIDTH)
self.x, self.y = self.enemy_rect.topleft
# [...]
def enemyMovement(self, player_x, player_y):
ene_x, ene_y = player_x - self.x, player_y - self.y
dist = math.hypot(ene_x, ene_y)
ene_x, ene_y = ene_x / dist, ene_y / dist
self.x += ene_x * self.ENEMY_ACCELERATION
self.y += ene_y * self.ENEMY_ACCELERATION
self.enemy_rect = round(self.x), round(self.y)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…