0

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.

Bob
  • 22,810
  • 38
  • 143
  • 225
user1237200
  • 149
  • 4
  • 13
  • Thanks for the answers, they are both really good :) I'm a bit stuck though, I'm getting results like: 0.130292159729 for the angle but that can't be right can it? I can't see any rotation for the sprites :/ – user1237200 Sep 19 '12 at 08:44
  • 1
    Maybe you need to convert the result to degree; `math.atan2(y,x) / math.pi * 180` – wrongite Sep 19 '12 at 10:19

2 Answers2

3

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)
Mu Mind
  • 10,935
  • 4
  • 38
  • 69
2

Using math.atan2() with the delta y and x will give you the appropriate angle in radians.

>>> math.atan2(1, -1)
2.356194490192345
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358