问题
I am creating a game where I want an enemy to path track onto the player - who can move in any direction on the 2D plane. At first, I tried...
self.bat_x += (player_rect.centerx - self.rect.centerx) / 60
self.bat_y += (player_rect.centery - self.rect.centery) / 60
Here the path-tracking works fine. I divide each value by 60 so that the enemy doesn't just appear and stick on to my player / to slow the movement of the enemy down. However, the further away the enemy is, the faster it is. The closer the bat gets, the slower the bat gets. This is because, using the x-axis for example, when the distance between the player and the enemy is smaller, player_rect.centerx - self.rect.centerx
is smaller so less gets added to self.bat_x
. Is there a way so that the path-finding still works but the speed is constant? Or does anyone know a different path-finding method and how to implement it?
回答1:
One way would be using the locations of the player and enemy to find the slope/angle of the line connecting them.
Considering that enemy is at (x1, y1) and player is at (x2, y2). Then
angle = arctan((y2 - y1)/x2-x1))
Note that x2 - x1 could be zero, so take care of that case.
After finding the line, you could use polar coordinates to find the next position
For eg
x += speed * sin(angle)
Y += speed * cos(angle)
回答2:
Pythagoras is your friend
x = player_rect.centerx - self.rect.centerx
y = player_rect.centery - self.rect.centery
norm = (x**2 + y**2)**0.5
const = 1/60
self.bat_x += const * x / norm
self.bat_y += const * y / norm
来源:https://stackoverflow.com/questions/61015832/path-finding-in-2d-space