Search code examples
pythonpygletgame-ai

How to find what direction the player is in from an enemy?


I have managed to get the enemy ai moving towards the player using this code (python and pyglet):

(dx, dy) = ((player.x - self.x)/math.sqrt((player.x - self.x) ** 2 + 
           (player.y - self.y) ** 2),(player.y - self.y)/math.sqrt((player.x - self.x)
           ** 2 + (player.y - self.y) ** 2))
newCoord = (self.x + dx * 3, self.y + dy * 3)
self.x,self.y = newCoord

However I am unsure of how to rotate the enemy sprite so they are facing the player. I am pretty sure that I could use some of the code above and rotate the player accordingly but I haven't been able to find a way that works.


Solution

  • The information you have is 2 legs of a right triangle, and you are trying to find the angle. So

    math.tan(angle) == float(player.y - self.y) / (player.x - self.x)
    

    or

    angle == math.atan(float(player.y - self.y) / (player.x - self.x))
    

    But this atan will lose sign information, and dividing may give you ZeroDivisionError, which is exactly what math.atan2 is for:

    angle = math.atan2(player.y - self.y, player.x - self.x)