Skip to content

Instantly share code, notes, and snippets.

@DataGreed
Created October 31, 2020 16:20
Show Gist options
  • Save DataGreed/77e1330fb661821196f1e4ba66774354 to your computer and use it in GitHub Desktop.
Save DataGreed/77e1330fb661821196f1e4ba66774354 to your computer and use it in GitHub Desktop.
Navmesh utils - GetRandomPointInRadius , CalculatePathLength
using UnityEngine.AI;
using UnityEngine;
namespace pro.datagreed.utils
{
public static class NavMeshUtil
{
// Get Random Point on a Navmesh surface in the specified radius
public static Vector3 GetRandomPointInRadius(Vector3 center, float maxDistance)
{
// Get Random Point inside Sphere which position is center, radius is maxDistance
Vector3 randomPos = Random.insideUnitSphere * maxDistance + center;
NavMeshHit hit; // NavMesh Sampling Info Container
// from randomPos find a nearest point on NavMesh surface in range of maxDistance
NavMesh.SamplePosition(randomPos, out hit, maxDistance, NavMesh.AllAreas);
return hit.position;
}
/// <summary>
/// Calculates walking path length between two points on a navmesh.
/// Useful for checking e.g. how long the sound should travel to attract attention of
/// the enemy
/// based on https://www.youtube.com/watch?v=mBGUY7EUxXQ&ab_channel=Unity
/// </summary>
/// <param name="sourcePosition"></param>
/// <param name="targetPosition"></param>
/// <param name="areaMask"></param>
/// <returns></returns>
public static float CalculatePathLength(Vector3 sourcePosition, Vector3 targetPosition, int areaMask=NavMesh.AllAreas)
{
//based on https://www.youtube.com/watch?v=mBGUY7EUxXQ&ab_channel=Unity
NavMeshPath path = new NavMeshPath();
// if (nav.enabled)
// {
// nav.CalculatePath(targetPosition, path);
// }
NavMesh.CalculatePath(sourcePosition, targetPosition, areaMask, path);
Vector3[] allWayPoints = new Vector3[path.corners.Length+2];
//add source and destination points, so we can measure the distance between them and nearest corners if any
allWayPoints[0] = sourcePosition;
allWayPoints[allWayPoints.Length-1] = targetPosition;
for (int i = 0; i < path.corners.Length; i++)
{
allWayPoints[i+1] = path.corners[i];
}
float pathLength = 0f;
for(int i=0; i<allWayPoints.Length-1; i++)
{
pathLength+=Vector3.Distance(allWayPoints[i], allWayPoints[i+1]);
}
return pathLength;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment