Version: 2021.3

Vector3.SignedAngle

切换到手册
public static float SignedAngle (Vector3 from, Vector3 to, Vector3 axis);

参数

from 测量角度差的源向量。
to 测量角度差的目标向量。
axis 一个向量,其他向量将绕其旋转。

返回

float Returns the signed angle between from and to in degrees.

描述

Calculates the signed angle between vectors from and to in relation to axis.

The angle returned is the angle of rotation from the first vector to the second, when treating these first two vector inputs as directions. These two vectors also define the plane of rotation, meaning they are parallel to the plane. This means the axis of rotation around which the angle is calculated is the cross product of the first and second vectors (and not the 3rd "axis" parameter). You can use the "left hand rule" to determine the axis of rotation, given the two input vectors. The third input (named the “axis” parameter), gives you a way to provide a contextual direction to include in the calculation. This has the result of flipping the sign of the result depending on whether this third vector that you supply falls above or below the plane of rotation defined by the first two input vectors. Therefore the sign of the final result depends on two things: the order in which you supply the "from" and "to" vector, and the direction of the third "axis" vector.
Note: The angle returned will always be between -180 and 180 degrees, because the method returns the smallest angle between the vectors. That is, it will never return a reflex angle.

using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour { public Transform target;

void Update() { Vector3 targetDir = target.position - transform.position; Vector3 forward = transform.forward; float angle = Vector3.SignedAngle(targetDir, forward, Vector3.up); if (angle < -5.0F) print("turn left"); else if (angle > 5.0F) print("turn right"); else print("forward"); } }

另请参阅:Angle 函数。