converting the difference in vectors to between 0 and 1

左心房为你撑大大i 提交于 2021-02-04 07:27:05

问题


I'm working with two unit vectors but not sure how to calculate this. I need it so that if they point in the same direction the answer is 1, opposite directions the answer is 0, perpendicular (either up or down) the answer is 0.5, etc.

Examples: For two vectors (1,0) and (-1,0) (so, opposite vectors), the answer I get is 0. For two vectors (1,0) and (1/sqrt(2),1/sqrt(2)) (so, the unit vector pointing at a 45 degree angle) I get 0.25. For two vectors (0,1) and (-1,0) (so, perpendicular vectors) I get 0.5

Thank you for any help with this!


回答1:


Read about the Dot product 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 )

If 2 normalized vectors point in the same direction, then the dot product is 1, if the point in the opposite direction, the dot product is -1 and if the vectors are perpendicular then the dot product is 0.

In pygame the dot product can be computed by math.Vector2.dot(). If A and B are pygame.math.Vector2 objects:

uA = A.normalize()
uB = B.normalize()
AdotB = uA.dot(uB)

In the example above, AdotB is in range [-1.0, 1.0]. AdotB * 0.5 + 0.5 is in range [0.0, 1.0] and math.acos(AdotB) / math.pi + 1 maps the angle between A and B linearly to the range [0.0, 1.0].


Furthermore, pygame.math.Vector2.angle_to() calculates the angle to a given vector in degrees. A value in range [0.0, 2.0] dependent on the angle can be computed by

w = 1 - A.angle_to(B) / 180



回答2:


What you essentailly need is the angle of the two vectors, you can the scale that to your 0-1 interval from the 0-pi interval.

You have the identity:

a dot b = norm(a)*norm(b)*cos(gamma), and in this case:
a dot b = cos(gamma), because they are unit vectors.

and

a dot b = ax*bx+ay*by

From this you have cos(gamma), and therefore gamma.

Does this help?



来源:https://stackoverflow.com/questions/64017147/converting-the-difference-in-vectors-to-between-0-and-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!