I can't waste the opportunity to say that many of these things are better implemented using vector algebra than angles. Angles are very intuitive, but code that uses them is often full of special cases that have to be dealt with using `if' statements, and they require using expensive calls to trigonometric functions.
I can't agree more: you may not know, but there is a little need of "school trigonometry" even in 3D, because everything can be done very elegantly using vectors. And all of it works on 2D, you just don't use Z axis.
If you store the locations for object a and b as vectors, you can:
- Get a distance between them by subtracting them and returning distance vector's length: (A-B).length() or (B-A).length()
- Get a direction A must go to to eventually get to B: (B-A).normalize() ("normalizing" always returns vector of length 1)
- Angle between two normalized vectors C and D is acos(C dot D).
And there are math libraries which already have all these operations written for vectors.
So if you need a rotation vector for your object to face your mouse, you would write something like this (assuming object position is in same space as mouse position):
#mousePos = ... #objectPos = ... initialLookDirection = Vector2(0, 1) # intitally your object looks "up", if Y axis is "up" targetLookDirection = (mousePos - objectPos).normalize() rotationInRadians = acos(initialLookDirection * targetLookDirection) # "*" is "dot" product in pygame Vector2
For pygame, you would use pygame.math.Vector2.