Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- private static int MAX_TRIES = 5;
- private static Vector3[] m_pathCorners = new Vector3[MAX_CORNERS];
- private static NavMeshPath m_navMeshPath = new NavMeshPath();
- //----------------------------------------------------------------------------------------
- public static bool GetNavMeshPosition(Vector3 _pos, int _areaMask, float _maxDistance, out Vector3 _navMeshPos)
- {
- NavMeshHit navMeshHit;
- if (NavMesh.SamplePosition(_pos, out navMeshHit, _maxDistance, _areaMask))
- {
- _navMeshPos = navMeshHit.position;
- return true;
- }
- _navMeshPos = Vector3.negativeInfinity;
- return false;
- }
- //----------------------------------------------------------------------------------------
- public static int CalculatePath(Vector3 _start, Vector3 _target, NavMeshQueryFilter _filter, Vector3[] _path, int _startIndex = 0, int _numTries = 0)
- {
- if (_numTries > MAX_TRIES || _startIndex >= m_pathCorners.Length)
- {
- if (_numTries > MAX_TRIES)
- Debug.Log("could not find a way from" + _start + " to " + _target + " in " + _numTries);
- else
- Debug.Log("could not find a way from" + _start + " to " + _target + " as" +_startIndex + "is samller or equal than" + m_pathCorners.Length);
- return -1;
- }
- var startPosOk = GetNavMeshPosition(_start, _filter.areaMask, MAX_PATH_DISTANCE, out Vector3 startPos);
- var endPosOk = GetNavMeshPosition(_target, _filter.areaMask, MAX_PATH_DISTANCE, out Vector3 targetPos);
- if (!startPosOk || !endPosOk)
- {
- Debug.Log("calculate path could not get proper navmesh position of start "+ _start + " and/or target position " + _target);
- return -1;
- }
- NavMesh.CalculatePath(startPos, targetPos, _filter, m_navMeshPath);
- switch (m_navMeshPath.status)
- {
- case NavMeshPathStatus.PathPartial:
- {
- var numCorners = m_navMeshPath.GetCornersNonAlloc(m_pathCorners);
- Array.Copy(m_pathCorners, 0, _path, _startIndex, numCorners);
- var lastPos = m_navMeshPath.corners[m_navMeshPath.corners.Length - 1];
- if (Math.Abs(lastPos.x - targetPos.x) < 0.5f && Math.Abs(lastPos.z - targetPos.z) < 0.5f)
- return _startIndex + numCorners;
- return CalculatePath(lastPos, _target, _filter, _path, _startIndex + numCorners, ++_numTries);
- }
- case NavMeshPathStatus.PathComplete:
- {
- var numCorners = m_navMeshPath.GetCornersNonAlloc(m_pathCorners);
- Array.Copy(m_pathCorners, 0, _path, _startIndex, numCorners);
- return _startIndex + numCorners;
- }
- default:
- {
- #if DEBUG
- Debug.Log("path invalid" + _start + " to " + _target + " in " + _numTries + " filter: " + _filter.areaMask);
- #endif
- return -1;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement