Search code examples
pythonpygameangle

Python Pygame find angle between two points


I am currently making a game which involves a sprite image to always face the mouse. I have looked everywhere for a function that does that, but I can't seem to find one. Is there a way to calculate an angle of difference from one point to another? Ex:

angleA_X, angleA_Y = (12, 52)
angleB_X, angleB_Y = (45, 11)

deltaX = angleB_X - angleA_X
deltaY = angleB_Y - angleA_Y

tan = deltaX/deltaY

formula = math.atan(tan)

formula = formula ** 2
formula = math.sqrt(formula)

formula = math.degrees(formula)

print(formula)

This would calculate the difference in the angle, but this does not return the right anwser. Any idea what is wrong?


Solution

  • You're doing some math operations that are not needed (such as ** 2 and sqrt), you just need math.atan2 (this will yield the angle in radians between A and B):

    math.atan2(angleA_Y - angleB_Y, angleA_X - angleB_X)
    

    math.atan2 has the benefit of also working when deltaX == 0.