The problem in your code is, that you use sine for determining the angle. For example the sine of 80° is the same as the sine of 100° (symmetric around 90°). That's why you code cannot distinguish between these two cases. The same problem holds for cos and tan.
If you really need to calculate the angle, then use atan2. This is a function that takes two arguments (x and y) and correctly calculates the angle of the corresponding line segment.
Code: Select all
distX = playerX - enemyX
distY = playerY - enemyY
angle = math.atan2(distX,distY)
However, in your case you don't even need to calculate the angle. Look: First you calculate the angle by an inverse of a trigonometric function and then you apply a trigonometric function to it, to get a vector again. You can save one step with the following approach:
First calculate the distance vector. Then calculate the distance and divide the distance vector by it. You get a vector of length one, that points into the desired direction. You then only have to multiply this by the movement speed of your enemy:
Code: Select all
distX = playerX - enemyX
distY = playerY - enemyY
distance = math.sqrt(distX*distX+distY*distY)
velocityX = distX/distance*speed
velocityY = distY/distance*speed
v.x = v.x + velocityX*dt
v.y = v.y + velocityY*dt
Note: The only case where you really need an angle, is when you want to rotate the image of your enemy. The love.graphics.draw routine needs an angle. In all other cases you can avoid calculating angles.