Reputation:
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?
Upvotes: 0
Views: 2623
Reputation: 142641
PyGame
has pygame.math.Vector2() which have angle_to()
import pygame
angleA_X, angleA_Y = (12, 52)
angleB_X, angleB_Y = (45, 11)
a = pygame.math.Vector2(angleA_X, angleA_Y)
b = pygame.math.Vector2(angleB_X, angleB_Y)
zero = pygame.math.Vector2()
print( zero.angle_to(a-b) ) # 128.8298249049704
Upvotes: 1
Reputation: 25023
If you really need an angle
angle = math.atan2(ymouse-ysprite, xmouse-xsprite)
if you rather need the sine and the cosine
dy, dx = ymouse-ysprite, xmouse-xsprite
r = math.hypot(dx, dy)
s, c = dy/r, dx/r
Upvotes: 0
Reputation: 11476
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
.
Upvotes: 3