Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Random point generator?

Discussion in 'Navigation' started by EnsurdFrndship, Sep 30, 2017.

  1. EnsurdFrndship

    EnsurdFrndship

    Joined:
    Apr 17, 2010
    Posts:
    786
    Hello,
    Is there a function than can return a Vector3 location of a random point along any navmesh?

    Thank you,
    Michael S. Lowe
     
  2. IngeJones

    IngeJones

    Joined:
    Dec 11, 2013
    Posts:
    129
    I use something like this (ignore some of the quirkiness for example the loop that was there ready for me to do stuff like testing for empty spot I haven't got round to). So I randomise the direction with the x and y negative or positive then simply generate a random number between the mindistance and maxdistance for distance away from the "from" starting point.

    Code (CSharp):
    1.  
    2. public static Vector3 FindLocation(Vector3 from, float mindistance, float maxdistance, bool empty)
    3.     {
    4.         int i = 0;
    5.         float x = 0f;
    6.         float z = 0f;
    7.         float y = from.y;
    8.         bool xneg;
    9.         bool zneg;
    10.         Vector3 newposition = new Vector3(x, y, z);
    11.         while (i < 20)
    12.         {
    13.             x = UnityEngine.Random.Range(mindistance, maxdistance);
    14.             xneg = (UnityEngine.Random.Range(1, 3) < 2);
    15.             z = UnityEngine.Random.Range(mindistance, maxdistance);
    16.             zneg = (UnityEngine.Random.Range(1, 3) < 2);
    17.             newposition.x = (xneg ? (from.x - x) : (from.x + x));
    18.             newposition.z = (zneg ? (from.z - z) : (from.z + z));
    19.             return newposition;
    20.             i++;
    21.         }
    22.         return newposition;
    23.     }
     
    Last edited: Oct 2, 2017
  3. IngeJones

    IngeJones

    Joined:
    Dec 11, 2013
    Posts:
    129
    How are we meant to format the code in this forum? I clicked "code editor" but it's still not indented.
     
  4. sylon

    sylon

    Joined:
    Mar 5, 2017
    Posts:
    246
    IngeJones likes this.
  5. IngeJones

    IngeJones

    Joined:
    Dec 11, 2013
    Posts:
    129
    Thanks, I have re-edited my post.
     
    drew081886 likes this.