• 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 jessee03 · Apr 05, 2013 at 03:33 AM · ai

Wandering AI

So I've been doing a little research about creating a wandering AI and was hoping someone knew a little bit more than me about setting one up. Here's the code for spawning an object in a random part of a circle radius

http://docs.unity3d.com/Documentation/ScriptReference/Random-insideUnitCircle.html

The problem is what if I want this circle to be applied to the area around an empty gameobject? Since I want enemies to walk around this set area instead. Also for the enemies movement would I just store a variable for that random location and then when the enemy reaches the location wait a random time before moving to a new location inside of the circle area.

Comment
Add comment
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

3 Replies

· Add your reply
  • Sort: 
avatar image
0

Answer by xt-xylophone · Apr 05, 2013 at 03:37 AM

http://unitygems.com/basic-ai-character/

This is what got me started on basic AI and a good place to go from IMO

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 xt-xylophone · Apr 05, 2013 at 03:37 AM 0
Share
 bool change; 
 float range;
 void Start () {
    range = 2f;
    target = GetTarget();
    InvokeRepeating ("NewTarget",0.01f,2.0f);
 }
 void Update () {        
    if(change)
        target = GetTarget ();
  
    if(Vector3.Distance(_transform.position,_target)>range){
       $$anonymous$$ove();
       animation.CrossFade("walk");
    }else animation.CrossFade ("idle");
 }
 Vector3 GetTarget(){
    return new Vector3(Random.Range (0,300),0,Random.Range (0,300));
 }
 void NewTarget(){
    int choice = Random.Range (0,3);
    switch(choice){
       case 0: 
          change = true;
          break;
       case 1: 
          change = false;
          break;
       case 2:
          target = _transform.position;
          break;
    } 
 }
avatar image jessee03 · Apr 05, 2013 at 03:59 AM 0
Share

This kind of helps me out but I still need help explaining how to setup the random circle radius from an empty gameobject location so my enemy can calculate where to walk towards.

avatar image xt-xylophone · Apr 05, 2013 at 04:07 AM 0
Share

Well at the moment the get target function is essentially getting a random point in a square thats 300 wide/long and centered at (150,150).

So for a circle distance from a certain object just changed that random.range to your circle function and maybe define your 'empty gameobject' as a public variable in the AI script so the bot always knows the area it needs to be wandering in.

avatar image
0

Answer by Fahir · Oct 10, 2021 at 03:31 PM

I have created a detailed article on this topic, you can check it out here: https://awesometuts.com/blog/unity-enemy-ai/

Feel free to use the code and the examples in the article in your project however you want.

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
0

Answer by atcarter714 · Oct 20, 2021 at 11:41 AM

I'll give you a simple solution I learned from an expert AI programmer. What you're doing is creating a virtual circle in front of your AI with a given radius and ahead of the character by a certain distance. Frame by frame you pick a random point along the curve of the circle and make the NavMeshAgent steer toward it. A factor for "jitter" determines how much randomness and direction changing takes place. By adjusting the values of the circular radius, the distance ahead and the jitter you can figure out the right type of wandering behavior for your NPC AI character by simply changing the values in the editor and watching how they move around. Experiment with the values until it looks right.


 [SerializeField] float circRadius = 10f;    // Radius of target circle
 [SerializeField] float circDistance = 10f;    // Distance of circle in front of the AI agent
 [SerializeField] float wanderJitter = 1f;    // Amount of random jitter in steering
 
 Vector3 aiWanderGoal = Vector3.Zero;
 
 void WanderAround() {
 
     /* We project a (mathematical) circle in front of the AI agent with a size of circRadius
      * and a distance in front of circDistance. We then pick a random place along the curve
      * of the circle to move toward, randomized by the factor of wanderJitter ...
      */
 
     aiWanderGoal += new Vector3( Random.Range( -1.0f, 1.0f ) * wanderJitter, 0f,
         Random.Range( -1.0f, 1.0f ) * wanderJitter );
 
     aiWanderGoal.Normalize();
     aiWanderGoal *= circRadius;
 
     var locTarget = aiWanderGoal + new Vector3( 0, 0, circDistance );
     var worldCoord = gameObject.transform.InverseTransformVector( locTarget );
 
     MoveTo( worldCoord );
 }
 
 void MoveTo( Vector3 location ) {
     
     // This is your own code that tells the NavMeshAgent where to go ...
     // But it could be as simple as this:
     navMeshAgent.SetDestination( location );
 }



Another approach is to spawn a randomized Vector3 every so often and set it as the NavMeshAgent destination, but you have to be careful your target won't be invalid (i.e., not on the terrain or navigable surface of the world) and clamp the values down to a certain range. This has worked decently for me in some larger open world terrains and I used terrain height sampling to find the correct Y value of the target point. Set a reasonable stopping distance for the agent in your world that works well: they don't need to get directly on top of their goal/destination unless that's important (like you need them standing on an exact spot for a cut scene or something.

Good luck!

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 atcarter714 · Oct 20, 2021 at 11:44 AM 0
Share

Note: Update would call WanderAround(); while you want the NPC to randomly wander around. This could even be expanded in a game where you want AI to explore the map, like in an RTS with "fog of war" by weighting the target point toward unexplored areas. The same thing could be done by weighting the point toward the player if you want the AI to appear to be randomly searching for the player after hearing/detecting them. Really good AI can be built up by combining lots of simple and cleanly written behaviors!

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

14 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

Related Questions

Can't properly duplicate an enemy AI 0 Answers

free roaming enemy ai 1 Answer

Can you bake nav mesh in prefab mode? 0 Answers

Objects jump when game is started 0 Answers

Move NavMeshAgent at a constant speed 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