简体   繁体   中英

How to get the angle between two vectors in pygame?

I want my player to look towards some certain coordinates in pygame. I tried to do this by getting the angle between the position of the player and the coordinates and then rotating it the player by that angle. I used a function for this,the function works properly when I need my player to look towards the coordinates of the mouse, but fails when i use the same function to make a zombie look towards the player. This was the function that is used.

def rotate_char(khiladi,vector,old_center,angle=False) :
x1, y1 = vector
x2, y2 = khiladi.pos
dx, dy = x2 - x1, y2 - y1

rads = atan2(dx, dy)
degs = degrees(rads)

r_khiladi = pygame.transform.rotate(khiladi.image, degs)

R_k = r_khiladi.get_rect()
R_k.center = old_center
screen.blit(r_khiladi, (R_k))
if angle : return degs 

I used another method that used numpy

v1_u = list(khiladi.pos / linalg.norm(khiladi.pos))
v2_u = list(vector / linalg.norm(vector))
v1_u[1] , v2_u[1] = -v1_u[1] , -v2_u[1]
c_angle =  degrees(arccos(clip(dot(v1_u, v2_u), -1.0, 1.0)))

When I tried to print the angles they were totally off mark and didn't even showed any pattern. Please Help

I recommend to use pygame.math.Vector2 / angle_to() to compute the angle between 2 vectors in degrees.

If (x1, y1) and (x2, y2) are 2 vectors, then the angle between the vectors is:

v1 = pygame.math.Vector2(x1, y1)
v2 = pygame.math.Vector2(x2, y2)
angle_v1_v2_degree = v1.angle_to(v2)

In general The dot product of 2 vectors is equal the cosine of the angle between the 2 vectors multiplied by the magnitude (length) of both vectors.

dot( A, B ) == | A | * | B | * cos( angle_A_B ) 

This follows, that the dot product of 2 unit vectors is equal the cosine of the angle between the 2 vectors, because the length of a unit vector is 1.

uA = normalize( A )
uB = normalize( B )
cos( angle_A_B ) == dot( uA, uB )

A 点 B

Hence the angle between 2 vectors can be computed by math.acos of the dot product of the 2 normalized vectors ( normalize() ):

v1 = pygame.math.Vector2(x1, y1)
v2 = pygame.math.Vector2(x2, y2)
v1u_dot_v2u = v1.normalize().dot(v2.normalize())
angle_v1_v2_radian = math.acos(v1u_dot_v2u)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM