#unity/日常积累

Vector3.SignedAngle

public static float SignedAngle (Vector3 from, Vector3 to, Vector3 axis);

参数

from

测量角度差的源向量。

to

测量角度差的目标向量。

axis

一个向量,其他向量将绕其旋转。

描述

返回 from 与 to 之间的有符号角度(以度为单位)。

返回两个向量之间的两个可能角度中的较小者,因此结果永远不会大于 180 度或小于 -180 度。 如果将 from 和 to 向量想象成一张纸上的线条,两者都源自同一点,则 axis 向量将指向纸外方向。 两个向量之间测量的角度在顺时针方向上为正,在逆时针方向上为负。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
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");
    }
}