Search code examples
pythonmathpygamepath-finding

Path-finding in 2D space


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.centerxis 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?


Solution

  • 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