using UnityEngine;
|
using UnityEngine.AI;
|
|
public class PathFinder
|
{
|
public static Vector3 AdjustPosition(Vector3 position)
|
{
|
NavMeshHit _navMeshHit;
|
position.y = 0;
|
if (NavMesh.SamplePosition(position, out _navMeshHit, 10, NavMesh.AllAreas))
|
{
|
return _navMeshHit.position;
|
}
|
return position;
|
}
|
|
private static NavMeshPath _path = new NavMeshPath();
|
public static bool WalkAble(Vector3 source, Vector3 dest, float dist = 0.01f)
|
{
|
source.y = 0;
|
dest.y = 0;
|
NavMesh.CalculatePath(source, dest, -1, _path);
|
if (_path.corners != null && _path.corners.Length > 0)
|
{
|
return MathUtility.DistanceSqrtXZ(dest, _path.corners[_path.corners.Length - 1]) < dist;
|
}
|
return false;
|
}
|
|
public static float CalculateDistance(Vector3 start, Vector3 dest)
|
{
|
float _dis = float.MaxValue;
|
start.y = 0;
|
dest.y = 0;
|
NavMesh.CalculatePath(start, dest, -1, _path);
|
if (_path.corners != null && _path.corners.Length > 1)
|
{
|
_dis = 0;
|
for (int i = 0; i < _path.corners.Length - 1; ++i)
|
{
|
_dis += Vector3.Distance(_path.corners[i], _path.corners[i + 1]);
|
}
|
}
|
return _dis;
|
}
|
|
public static bool TryGetValidDest(Vector3 start, Vector3 dest, ref Vector3 validDest)
|
{
|
dest = AdjustPosition(dest);
|
start.y = 0;
|
dest.y = 0;
|
NavMesh.CalculatePath(start, dest, -1, _path);
|
if (_path.corners != null && _path.corners.Length > 0)
|
{
|
validDest = _path.corners[_path.corners.Length - 1];
|
return true;
|
}
|
return false;
|
}
|
}
|