78 lines
2.1 KiB
C#
78 lines
2.1 KiB
C#
using System;
|
||
using System.Collections;
|
||
using System.Collections.Generic;
|
||
using Unity.VisualScripting;
|
||
using UnityEngine;
|
||
|
||
public class CalcTool
|
||
{
|
||
/// <summary>
|
||
/// 旋转选最近的角度
|
||
/// </summary>
|
||
/// <param name="toY">将要旋转到的角度</param>
|
||
/// <param name="orgY">当前角度</param>
|
||
/// <returns></returns>
|
||
public static float FixEulerAngle(float toY, float orgY)
|
||
{
|
||
float angleDiff = toY - orgY;
|
||
float absAngleDiff = Mathf.Abs(angleDiff);
|
||
//使toY和orgY在同一个360度的范围内,即同一圈,方便下面计算
|
||
if (absAngleDiff > 360)
|
||
{
|
||
toY = 360 * Mathf.Floor(orgY / 360) + toY % 360;
|
||
angleDiff = toY - orgY;
|
||
absAngleDiff = Mathf.Abs(angleDiff);
|
||
}
|
||
|
||
// 增补值
|
||
// 方向修正
|
||
// 调整目标角度使之最短路径
|
||
if (absAngleDiff > 180)
|
||
{
|
||
if (angleDiff < 0)
|
||
{
|
||
toY += 360;
|
||
}
|
||
else
|
||
{
|
||
toY -= 360;
|
||
}
|
||
}
|
||
|
||
// if (Math.abs(toY) >= Number.MAX_VALUE) {
|
||
// toY %= 360
|
||
// }
|
||
// toY = Number.MAX_VALUE//debug
|
||
return toY;
|
||
}
|
||
|
||
// 核心判断方法:返回target是否在reference的前面或者相交
|
||
/// <param name="ignoreYAxis">是否忽略Y轴(仅判断水平方向)</param>
|
||
public static bool IsTargetFrontOrIntersect(Transform targetObj, Transform referenceObj, bool ignoreYAxis = true)
|
||
{
|
||
if (referenceObj == null || targetObj == null)
|
||
{
|
||
Debug.LogError("参考物体或目标物体未赋值!");
|
||
return false;
|
||
}
|
||
|
||
// 1. 计算目标相对于参考物体的方向向量
|
||
Vector3 targetDir = targetObj.position - referenceObj.position;
|
||
|
||
// 2. 忽略Y轴(可选,比如地面物体只看水平方向)
|
||
if (ignoreYAxis)
|
||
{
|
||
targetDir.y = 0;
|
||
}
|
||
|
||
// 3. 归一化方向向量(消除距离影响)
|
||
targetDir.Normalize();
|
||
|
||
// 4. 计算参考物体正前方与目标方向的点积
|
||
float dotProduct = Vector3.Dot(referenceObj.forward, targetDir);
|
||
|
||
// 5. 点积<0 → 目标在前方或者重合
|
||
return dotProduct >= 0;
|
||
}
|
||
}
|