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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…