Search Unity

Even distribution for random points within NavMesh area

Discussion in 'Navigation' started by Karrzun, Dec 30, 2019.

  1. Karrzun

    Karrzun

    Joined:
    Oct 26, 2017
    Posts:
    129
    Hi everyone,

    I'm trying to get a random point on a NavMesh that is 1) within a certain radius around a given point and 2) within a given area of the NavMesh. A little vizualisation: I want a random point within the circle around the purple Center Point that is on the green area.

    RandomPoint.png

    Currently I'm achieving this with the following code that is attached to the Center Point.

    Code (CSharp):
    1.  
    2.     // the radius paramter defines the size of the circle
    3.     public Vector3 GetRandomPosition (float radius)
    4.     {
    5.         Vector3 pos = transform.position;
    6.         Vector2 randomOffset = Random.insideUnitCircle * radius;
    7.  
    8.         pos.x += randomOffset.x;
    9.         pos.z += randomOffset.y;
    10.  
    11.         NavMeshHit navInfo;
    12.         // the LevelManager.Instance.AreaMask parameter defines the walkable area
    13.         if (!NavMesh.SamplePosition (
    14.             pos,
    15.             out navInfo,
    16.             float.MaxValue,
    17.             LevelManager.Instance.AreaMask))
    18.         {
    19.             // should never occur, but in case of an emergency
    20.             // return the position of the center point as this is
    21.             // confirmed to fulfill all constraints beforehand
    22.             return transform.position;
    23.         }
    24.  
    25.         return navInfo.position;
    26.     }

    Now, this code works and does what it's supposed to do but there's one problem, obviously. The bigger the Non Walkable area gets, the less evenly distributed are the returned positions as all initially generated random positions that area invalid get "shifted" towards the edge betweens Walkable and Non Walkable area by NavMesh.SamplePosition ().
    I've found solutions on how to evenly distribute random positions on a NavMesh on Google but none of them took a search radius into consideration and so far I couldn't come up with a solution on my own.

    Does anybody have an idea how to do this?


    Thank you in advance!