将向量的差值转换为 0 和 1 之间 [英] converting the difference in vectors to between 0 and 1

查看:34
本文介绍了将向量的差值转换为 0 和 1 之间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理两个单位向量,但不确定如何计算.我需要它,以便如果它们指向相同的方向,答案是 1,相反的方向,答案是 0,垂直(向上或向下)答案是 0.5,等等.

示例:对于两个向量 (1,0) 和 (-1,0)(所以,相反的向量),我得到的答案是 0.对于两个向量 (1,0) 和 (1/sqrt(2),1/sqrt(2))(因此,单位向量指向 45 度角)我得到 0.25.对于两个向量 (0,1) 和 (-1,0)(所以,垂直向量)我得到 0.5

感谢您对此的任何帮助!

解决方案

阅读关于

如果 2 个归一化向量指向同一个方向,则点积为 1,如果指向相反方向的点,点积为 -1,如果向量垂直则点积为 0.

在 pygame 中,可以通过 计算点积math.Vector2.dot().如果 ABpygame.math.Vector2 对象:

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


在上面的例子中,AdotB 的范围是 [-1.0, 1.0].AdotB * 0.5 + 0.5 在范围 [0.0, 1.0] 和 math.acos(AdotB)/math.pi + 1 映射 A 之间的角度code> 和 B 线性到范围 [0.0, 1.0].


此外,pygame.math.Vector2.angle_to() 计算给定向量的角度(以度为单位).依赖于角度的范围 [0.0, 2.0] 中的值可以通过

计算

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

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!

解决方案

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

这篇关于将向量的差值转换为 0 和 1 之间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆