Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • 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 /
This post has been wikified, any user with enough reputation can edit it.
avatar image
0
Question by Ouija · Feb 22, 2015 at 04:49 AM · animationanimatorplaywaypoint

Different animation on each wayPoint

Today's the day I start learning how to work with animation. I am attempting to play a different animation once the Char. reaches a wayPoint. Each wayPoint will have its own animation. I am wondering if this should be done in the script? or with the animator somehow? Anyone with ideas or examples would be awesome.

 using UnityEngine;
 using System.Collections;
 using UnityEngine.UI;
 
 public class DoneEnemyAI : MonoBehaviour
 {
     
     public float patrolSpeed = 2f;                            // The nav mesh agent's speed when patrolling.
     public float chaseSpeed = 5f;                            // The nav mesh agent's speed when chasing.
     public float runSpeed = 10f;
     public float chaseWaitTime = 5f;                        // The amount of time to wait when the last sighting is reached.
     public float patrolWaitTime = 1f;                        // The amount of time to wait when the patrol way point is reached.
     public Transform[] patrolWayPoints;                        // An array of transforms for the patrol route.
     public float waitTime;
     public float distanceLimit;
     private DoneHashIDs hash;    
     private DoneEnemySight enemySight;                        // Reference to the EnemySight script.
     private NavMeshAgent nav;                                // Reference to the nav mesh agent.
     private Transform player;                                // Reference to the player's transform.
     private DoneLastPlayerSighting lastPlayerSighting;        // Reference to the last global sighting of the player.
     private float chaseTimer;                                // A timer for the chaseWaitTime.
     private float patrolTimer;                                // A timer for the patrolWaitTime.
     private int wayPointIndex;                                // A counter for the way point array.
     private bool isClicked;
     private bool canCheckDistance;
     private Vector3 posToCheck;
     private Animator anim;
     GameObject[] markers;
     GameObject[] way1;
     private bool waitTimeSet = false;
     private int lastPoint = -1; // put at the top
 
 
     void Awake ()
     {
 
         anim = GetComponent<Animator>();
         hash = GameObject.FindGameObjectWithTag(DoneTags.gameController).GetComponent<DoneHashIDs>();
         markers = GameObject.FindGameObjectsWithTag("marker");
         // Setting up the references.
         enemySight = GetComponent<DoneEnemySight>();
         nav = GetComponent<NavMeshAgent>();
         player = GameObject.FindGameObjectWithTag(DoneTags.player).transform;
         way1 = GameObject.FindGameObjectsWithTag("way1");
         lastPlayerSighting = GameObject.FindGameObjectWithTag(DoneTags.gameController).GetComponent<DoneLastPlayerSighting>();
         isClicked = false;
     }
     
     void OnMouseDown()
     {
         isClicked = true;
         StartCoroutine(WaitForSomeTime());
         Vector3 markerPos = markers[Random.Range(0, markers.Length)].transform.position;
         GetComponent<NavMeshAgent>().destination =  markerPos;
         posToCheck = markerPos;
         canCheckDistance = true;
 
     }
 
     void Update ()
     {
             if (isClicked) {
                 Running ();
             } else if (enemySight.playerInSight) {
                 if (!isClicked) 
             //    Running ();
                 Shooting ();     
             } else if (enemySight.personalLastSighting != lastPlayerSighting.resetPosition) {
                 if (!isClicked) 
                     Chasing ();
             } else {
                 if (!isClicked) 
                  
                     Patrolling ();
             }     
         }
 
 
     void Running ()
     {
         nav.speed = runSpeed;
         if (canCheckDistance) {
 
             if (Vector3.Distance (transform.position, posToCheck) > distanceLimit - 0.5f) {
                 isClicked = false;
                 canCheckDistance = false;
             }
         }
     }
     void Shooting ()
     {
         // Stop the enemy where it is.
         nav.Stop();
     }
     
     void Chasing ()
     {
         // Create a vector from the enemy to the last sighting of the player.
         Vector3 sightingDeltaPos = enemySight.personalLastSighting - transform.position;
         
         // If the the last personal sighting of the player is not close...
         if(sightingDeltaPos.sqrMagnitude > 4f)
             // ... set the destination for the NavMeshAgent to the last personal sighting of the player.
             nav.destination = enemySight.personalLastSighting;
         
         // Set the appropriate speed for the NavMeshAgent.
         nav.speed = chaseSpeed;
         
         // If near the last personal sighting...
         if(nav.remainingDistance < nav.stoppingDistance)
         {
             // ... increment the timer.
             chaseTimer += Time.deltaTime;
             
             // If the timer exceeds the wait time...
             if(chaseTimer >= chaseWaitTime)
             {
 
                 chaseWaitTime = Random.Range(4,31);
 
                 // ... reset last global sighting, the last personal sighting and the timer.
                 lastPlayerSighting.position = lastPlayerSighting.resetPosition;
                 enemySight.personalLastSighting = lastPlayerSighting.resetPosition;
                 chaseTimer = 0f;
             }
         }
         else
             // If not near the last sighting personal sighting of the player, reset the timer.
             chaseTimer = 0f;
     }
     
     void Patrolling ()
     {
         // Set an appropriate speed for the NavMeshAgent.
         nav.speed = patrolSpeed;
         
         // If near the next waypoint or there is no destination...
         if(nav.remainingDistance < nav.stoppingDistance)
         {
             
             if(!waitTimeSet)
             {
                 patrolWaitTime = Random.Range(2,4);
                 anim.SetBool(patrolWayPoints[wayPointIndex].name, true);
                 //Debug.Log (patrolWayPoints[wayPointIndex].name);
                 patrolTimer = 0;
                 waitTimeSet = true;
             }
             
             // ... increment the timer.
             patrolTimer += Time.deltaTime;
             
             //Debug.Log (patrolTimer);
             // If the timer exceeds the wait time...
             if(patrolTimer >= patrolWaitTime)
             {
                 anim.SetBool(patrolWayPoints[wayPointIndex].name, false);
                 if(wayPointIndex != null)
                     lastPoint = wayPointIndex;
                 
                 wayPointIndex = Random.Range(0, patrolWayPoints.Length);
                 //Debug.Log ("before last = " + lastPoint + " new = " + wayPointIndex);
                 if(lastPoint == wayPointIndex)
                 {
                     int[] tempIntArray = new int[patrolWayPoints.Length - 1];
                     int cnt = 0;
                     for (int i = 0; i < patrolWayPoints.Length; i++)
                     {
                         if(i != lastPoint)
                         {
                             tempIntArray[cnt] = i;
                             cnt ++;
                         }
                         wayPointIndex = tempIntArray[Random.Range (0,tempIntArray.Length)];
                     }
                     //Debug.Log ("after last = " + lastPoint + " new = " + wayPointIndex);
                 }
                 nav.destination = patrolWayPoints[wayPointIndex].position;
                 waitTimeSet = false;
             }
         }
         else
         {
             patrolTimer = 0;
         }
     }
 
 IEnumerator WaitForSomeTime()
     {
         waitTime = Random.Range(4,31);
 
     yield return new WaitForSeconds(waitTime);
     isClicked = false;
 }
 }
 
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

1 Reply

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

Answer by Mmmpies · Feb 22, 2015 at 11:48 AM

Are you using mecanim or legacy animations?

Really I'd recommend you use mecanim if available, just create a set of bool parameters for each way point (e.g. Way1, Way2, Way3, Way4 etc) and when you arrive at the way point use

 anim.SetBool("Way1" , true);

and just set to false when your wait time is over.

Comment
Add comment · Show 39 · 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 Ouija · Feb 22, 2015 at 02:45 PM 0
Share

Thanks for the reply! Yes sir, I am using mecanim.

So what would be happening exactly, I set up parameter in the animator, assign an animation to that parameter, set it as false?

and the example of script you wrote, should gooo jsut under Void Patrolling?

Sorry new to the animation thing, trying to wrap my head around it

avatar image Mmmpies · Feb 22, 2015 at 03:32 PM 0
Share

Then first @Ouija watch this $$anonymous$$ecanimTutorial

Your script will need:

 private Animator anim;
 
 void Start()
 {
     anim = gameObject.GetComponent<Animator>();
 }
 
 //then in the main part, I think this should be right if at way1
 
 // ... increment the timer.
 patrolTimer += Time.deltaTime;
 
 anim.SetBool("Way1", true);
 
 
 
 // and to stop it
 
 // Reset the timer.
 patrolTimer = 0;
 
 anim.SetBool("Way1", false);

You will need a way of identifying which wayPoint you're at but that's just general program$$anonymous$$g and not mecanim.

As for the Animator put your animations on there and set transitions from patrolling to Way1, Way2 etc. Like this:

Patrol

But that tutorial will help you more so watch it first.

mecanimpatrol.png (30.7 kB)
avatar image Ouija · Feb 22, 2015 at 04:06 PM 0
Share

Epic answer dude. So I am doing this with the S$$anonymous$$lth package comes with unity. The mecanim is already set up. And there is a locomotion where I am assu$$anonymous$$g you have "Patrol" too? I am first testing with one wayPoint. Should the condition be way1, true?

alt text

also, in order to find the waypoint, think findWithTag would work any sense?

anim.png (76.1 kB)
avatar image Mmmpies · Feb 23, 2015 at 06:14 PM 1
Share

Right so there are errors all over the place but it plays, I don't know how! ;¬)

O$$anonymous$$ first error is the condition in the Animator to go back to locomotion is set to ExitTime, it should be set to the waypoint bool false.

Next, and this one foxed me for a bit. The Nav$$anonymous$$esh stopping distance is O$$anonymous$$ but the robot stops so fast it's right on the edge of the distance and floating point calculations being a bit funky it was dropping out of the loop and resetting the patrolTimer to 0. That's O$$anonymous$$ we only need to trigger that we reach the waypoint and we can use the waitTimeSet bool for the rest of it.

 if(nav.remainingDistance < nav.stoppingDistance || waitTimeSet)
avatar image Ouija · Feb 23, 2015 at 08:28 PM 1
Share

Should be ticked now!

Show more comments

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.

Follow this Question

Answers Answers and Comments

21 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

Related Questions

Animation doesn't play 1 Answer

How do I play my animations w. Mechanim? 1 Answer

Using Animator, How To Play an Animation Backwards 1 Answer

2D Animation does not start 1 Answer

Animation not be found 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