49 lines
1.7 KiB
C#
49 lines
1.7 KiB
C#
using UnityEngine;
|
||
|
||
namespace NBF
|
||
{
|
||
public static class GameUtils
|
||
{
|
||
public static float GetVerticalAngle(Transform character, Transform target)
|
||
{
|
||
// 计算从角色指向目标的向量
|
||
Vector3 direction = target.position - character.position;
|
||
|
||
// 计算水平距离(XZ平面)
|
||
float horizontalDistance = new Vector3(direction.x, 0, direction.z).magnitude;
|
||
|
||
// 计算垂直高度差(Y轴)
|
||
float verticalDistance = direction.y;
|
||
|
||
// 使用反正切计算垂直角度
|
||
// Atan2(垂直距离, 水平距离)
|
||
float angle = Mathf.Atan2(verticalDistance, horizontalDistance) * Mathf.Rad2Deg;
|
||
|
||
return angle; // 正值为上方,负值为下方
|
||
}
|
||
|
||
public static float GetHorizontalAngle(Transform obj1, Transform obj2)
|
||
{
|
||
// 获取两个物体在水平面上的位置向量
|
||
Vector3 pos1 = obj1.position;
|
||
Vector3 pos2 = obj2.position;
|
||
|
||
// 创建水平方向向量(忽略Y轴)
|
||
Vector3 direction = new Vector3(
|
||
pos2.x - pos1.x,
|
||
0, // Y轴设为0,只在XZ平面计算
|
||
pos2.z - pos1.z
|
||
);
|
||
|
||
// 计算相对于世界坐标系前向向量的角度
|
||
float angle = Vector3.SignedAngle(
|
||
Vector3.forward, // 参考方向(世界坐标系前向)
|
||
direction.normalized,
|
||
Vector3.up // 旋转轴(Y轴)
|
||
);
|
||
|
||
// 返回角度范围:-180° 到 180°
|
||
return angle;
|
||
}
|
||
}
|
||
} |