UNITY3D兩個(gè)物體相對(duì)位置、角度、相對(duì)速度方向
2019/4/9??????點(diǎn)擊:
using UnityEngine;
using System.Collections;
// 兩物體相對(duì)位置判斷、追蹤相對(duì)速度方向、朝向等計(jì)算方向以及角度
public class Direction : MonoBehaviour {
public Vector3 V1;
public Vector3 V2;
void Start()
{
// 為了方便理解便于計(jì)算,將向量在 Y 軸上的偏移量設(shè)置為 0
V1 = new Vector3( 3, 0, 4);
V2 = new Vector3( -4, 0, 3);
// 分別取 V1,V2 方向上的 單位向量(只是為了方便下面計(jì)算)
V1 = V1.normalized;
V2 = V2.normalized;
// 計(jì)算向量 V1,V2 點(diǎn)乘結(jié)果
// 即獲取 V1,V2夾角余弦 cos(夾角)
float direction = Vector3.Dot(V1, V2);
Debug.LogError("direction : " + direction);
// 夾角方向一般?。? - 180 度)
// 如果取(0 - 360 度)
// direction >= 0 則夾角在 (0 - 90] 和 [270 - 360] 度之間
// direction < 0 則夾角在 (90 - 270) 度之間
// direction 無法確定具體角度
// 反余弦求V1,V2 夾角的弧度
float rad = Mathf.Acos(direction);
// 再將弧度轉(zhuǎn)換為角度
float deg = rad * Mathf.Rad2Deg;
// 得到的 deg 為 V1,V2 在(0 - 180 度的夾角)還無法確定V1,V2 的相對(duì)夾角
// deg 還是無法確定具體角度
// 計(jì)算向量 V1, V2 的叉乘結(jié)果
// 得到垂直于 V1, V2 的向量, Vector3(0, sin(V1,V2夾角), 0)
// 即 u.y = sin(V1,V2夾角)
Vector3 u = Vector3.Cross(V1, V2);
Debug.LogError("u.y : " + u.y);
// u.y >= 0 則夾角在 ( 0 - 180] 度之間
// u.y < 0 則夾角在 (180 - 360) 度之間
// u.y 依然無法確定具體角度
// 結(jié)合 direction >0 、 u.y > 0 和 deg 的值
// 即可確定 V2 相對(duì)于 V1 的夾角
if (u.y >= 0) // (0 - 180]
{
if (direction >= 0)
{
// (0 - 90] 度
}
else
{
// (90 - 180] 度
}
}
else // (180 - 360]
{
if (direction >= 0)
{
// [270 - 360]
// 360 + (-1)deg
}
else
{
// (180 - 270)
}
}
Debug.LogError(deg);
}
}
- 上一篇:unity3d角度偏移計(jì)算方法 2019/4/9
- 下一篇:UNITY3D 腳本實(shí)現(xiàn)鼠標(biāo)控制物體旋轉(zhuǎn) 2019/4/9
