• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by PvTGreg · Dec 18, 2014 at 06:00 PM · ainavmesh

pick random point on navmesh

hi ive looked at the other questions regarding this but havent found what i want i wish to pick a random point on the navmesh set that as my ai's destination and when he reaches it pick another random point has anyone found a way to do this? even if you only know how to check when ai has stoped or reached its destination id also like to know this

Comment
Add comment · Show 8
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image MakinStuffLookGood · Dec 18, 2014 at 07:51 PM 0
Share

Both of your questions are already answered on here:

http://answers.unity3d.com/questions/324589/how-can-i-tell-when-a-navmesh-has-reached-its-dest.html

http://answers.unity3d.com/questions/475066/how-to-get-a-random-point-on-navmesh.html

Edit: corrected second link to another question ins$$anonymous$$d of this one!

avatar image PvTGreg · Dec 18, 2014 at 08:06 PM 0
Share

first one i knew about but dosent explain how to use it second one is my question :P

avatar image vintar · Dec 18, 2014 at 08:17 PM 0
Share

I would use this for random point : http://docs.unity3d.com/ScriptReference/Random-insideUnitCircle.html and this to check if that random point is on the nav mesh : http://docs.unity3d.com/ScriptReference/Nav$$anonymous$$esh.SamplePosition.html

avatar image Xtro · Dec 18, 2014 at 08:18 PM 0
Share

Broxxar, you gave url of this very question :)

avatar image MakinStuffLookGood · Dec 18, 2014 at 08:22 PM 1
Share

Whoops! Thanks Xtro, had this question and the one with the answer open in two tabs and grabbed the wrong URL to post haha.

avatar image PvTGreg · Dec 19, 2014 at 11:43 AM 0
Share

but guys as i said i have already looked at theese and they dont work they dont tell me how to use theese thats what im asking how do i use this

avatar image vintar · Dec 19, 2014 at 02:20 PM 0
Share

Not sure about the formatting here so grab this script. I did this exact thing before. I used the simpleAI script free from asset store and modified it to check if the point is on the nav mesh.

https://dl.dropboxusercontent.com/u/56011417/WanderBehavior.cs

avatar image PvTGreg · Dec 20, 2014 at 09:16 PM 0
Share

i got it ill post it below

4 Replies

· Add your reply
  • Sort: 
avatar image
0
Best Answer

Answer by PvTGreg · Dec 20, 2014 at 09:16 PM

 if (DoWaypoints == true)
         {
             float dist = GetComponent<NavMeshAgent>().remainingDistance; 
             if (dist!=Mathf.Infinity && GetComponent<NavMeshAgent>().pathStatus== NavMeshPathStatus.PathComplete && GetComponent<NavMeshAgent>().remainingDistance==0)//Arrived.
             {
                 Wonder();
             }
         }



 void Wonder()
     {
         Vector3 randomDirection = Random.insideUnitSphere * walkRadius;
         randomDirection += transform.position;
         NavMeshHit hit;
         NavMesh.SamplePosition(randomDirection, out hit, walkRadius, 1);
         Vector3 finalPosition = hit.position;
         GetComponent<NavMeshAgent>().destination = finalPosition;
     }


Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
7

Answer by Puck · Feb 19, 2017 at 10:56 PM

For anyone coming here from Google, I encountered this same issue where I wanted to place my agents randomly on pathable terrain and I came up with the following solution for Unity 5.5.

 Vector3 GetRandomLocation()
     {
         NavMeshTriangulation navMeshData = NavMesh.CalculateTriangulation();
 
         // Pick the first indice of a random triangle in the nav mesh
         int t = Random.Range(0, navMeshData.indices.Length-3);
         
         // Select a random point on it
         Vector3 point = Vector3.Lerp(navMeshData.vertices[navMeshData.indices[t]], navMeshData.vertices[navMeshData.indices[t+1]], Random.value);
         Vector3.Lerp(point, navMeshData.vertices[navMeshData.indices[t+2]], Random.value);
 
         return point;
     }

The distribution isn't uniform, but it works well enough for my purpose.

Comment
Add comment · Show 3 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image mdevil · Mar 18, 2017 at 01:59 PM 0
Share

Thank you very much! That's cool method!

avatar image clamum · Nov 28, 2019 at 04:01 AM 0
Share

Awesome, thanks a ton!

avatar image YektaOz · May 23, 2021 at 08:20 PM 0
Share

thanks so much !

avatar image
1

Answer by batteryyrettab · Jun 08, 2018 at 01:04 AM

A modification to Puck's answer to make it a little more uniform is

     Vector3 GetRandomLocation()
     {
         NavMeshTriangulation navMeshData = NavMesh.CalculateTriangulation();
 
         int maxIndices = navMeshData.indices.Length - 3;
         // Pick the first indice of a random triangle in the nav mesh
         int firstVertexSelected = Random.Range(0, maxIndices);
         int secondVertexSelected = Random.Range(0, maxIndices);
         //Spawn on Verticies
         Vector3 point = navMeshData.vertices[navMeshData.indices[firstVertexSelected]];
 
         Vector3 firstVertexPosition = navMeshData.vertices[navMeshData.indices[firstVertexSelected]];
         Vector3 secondVertexPosition = navMeshData.vertices[navMeshData.indices[secondVertexSelected]];
         //Eliminate points that share a similar X or Z position to stop spawining in square grid line formations
         if ((int)firstVertexPosition.x == (int)secondVertexPosition.x ||
             (int)firstVertexPosition.z == (int)secondVertexPosition.z
             )
         {
             point = GetRandomLocation(); //Re-Roll a position - I'm not happy with this recursion it could be better
         }
         else
         {
             // Select a random point on it
             point = Vector3.Lerp(
                                             firstVertexPosition,
                                             secondVertexPosition, //[t + 1]],
                                             Random.Range(0.05f, 0.95f) // Not using Random.value as clumps form around Verticies 
                                         );
         }
         //Vector3.Lerp(point, navMeshData.vertices[navMeshData.indices[t + 2]], Random.value); //Made Obsolete
 
         return point;
     }
Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image batteryyrettab · Jun 08, 2018 at 01:11 AM 0
Share

Example usage might look like this: (including a variant to only spawn on certain areas of the Nav$$anonymous$$esh. Use 8, 16, 32, etc. for each layer)

 //Declare these:
 private Nav$$anonymous$$eshHit navmeshHit;
 public bool spawnOnArea = false;
 
 //Usage:
 
 for (int i = 0; i < 50; i++)
         {
             if (!spawnOnArea)
             {           GameObject.CreatePrimitive(PrimitiveType.Sphere).transform.position = GetRandomLocation();
             }
             else
             {
                 Vector3 spotToSpawn = GetRandomLocation();
                 if (Nav$$anonymous$$esh.SamplePosition(spotToSpawn, out navmeshHit, 1, Nav$$anonymous$$esh.AllAreas))
                 {
                     if (navmeshHit.mask == 8)
                     {                      GameObject.CreatePrimitive(PrimitiveType.Sphere).transform.position = spotToSpawn;
                     }
                 }
             }
         }
avatar image
0

Answer by Mmmpies · Dec 19, 2014 at 02:32 PM

That second one searches for the closest point on a navmesh to the given location but it takes a float to say how far away from the random location to check so just set that high enough and it'll find a valid location on the navmesh nearest to your random location.

Not sure how much performance hit it is though.

link text

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

36 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Multiple Cars not working 1 Answer

How to make AI walk around ingame built walls? 1 Answer

My NavMeshAgent doesn't move at all!,Why my NavMeshAgent doesn't move at all? 0 Answers

i can't set destination, using AI Navmesh via raycast 1 Answer

ZOMBIE AI SCRIPT 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges