Files
Fishing2/Assets/Scripts/Common/Utils/GameUtils.cs
2026-01-18 01:05:56 +08:00

49 lines
1.7 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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;
}
}
}