Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

A Waypoint Script Explained in Super Detail!

Discussion in 'Scripting' started by cherub, Jul 17, 2010.

  1. cherub

    cherub

    Joined:
    Apr 26, 2006
    Posts:
    493
    I have recently been really learning Unity Scripting.

    It is my first scripting language.

    I find it really hard to find any info that assumes complete and utter Noobfullness and the need to have my hand held through every step.

    So now that I have learned a few things, I thought there might be others out there like me, who something like this simple waypoint script might be usefull to.

    Almost every single line is commented on.
    The uncommented version is at the bottom.

    Just copy paste into your script editor.
    It is way more readable with the color formatting.

    I may add "super commented on" obstacle avoidance next.



    Code (csharp):
    1. //   This is a very simple waypoint system.
    2. //   Each bit is explained in as much detail as possible for people (like me!) who need every single line explained.
    3. //
    4. //   As a side note to the inexperienced (like me at the moment!), you can delete the word "private" on any variable to see it in the inspector for debugging.
    5. //
    6. //   I am sure there are issues with this as is, but it seems to work pretty well as a demonstration.
    7. //
    8. //STEPS:
    9. //1. Attach this script to a GameObject with a RidgidBody and a Collider.
    10. //2. Change the "Size" variable in "Waypoints" to the number of waypoints you want to use.
    11. //3. Drop your waypoint objects on to the empty variable slots.
    12. //4. Make sure all your waypoint objects have colliders. (Sphere Collider is best IMO).
    13. //5. Click the checkbox for "is Trigger" to "On" on the waypoint objects to make them triggers.
    14. //6. Set the Size (radius for sphere collider) or just Scale for your waypoints.
    15. //7. Have fun! Try changing variables to get different speeds and such.
    16. //
    17. //   Disclaimer:
    18. //   Extreeme values will start to mess things up.
    19. //   Maybe someone more experienced than me knows how to improve it.
    20. //   Please correct me if any of my comments are incorrect.
    21.  
    22.  
    23.  
    24.  
    25. var accel = 0.8; //This is the rate of accelleration after the function "Accell()" is called. Higher values will cause the object to reach the "speedLimit" in less time.
    26.  
    27. var inertia = 0.9; //This is the the amount of velocity retained after the function "Slow()" is called. Lower values cause quicker stops. A value of "1.0" will never stop. Values above "1.0" will speed up.
    28.  
    29. var speedLimit = 10.0; //This is as fast the object is allowed to go.
    30.  
    31. var minSpeed = 1.0; //This is the speed that tells the functon "Slow()" when to stop moving the object.
    32.  
    33. var stopTime = 1.0; //This is how long to pause inside "Slow()" before activating the function "Accell()" to start the script again.
    34.  
    35. //This variable "currentSpeed" is the major player for dealing with velocity.
    36. //The "currentSpeed" is mutiplied by the variable "accel" to speed up inside the function "accell()".
    37. //Again, The "currentSpeed" is multiplied by the variable "inertia" to slow things down inside the function "Slow()".
    38. private var currentSpeed = 0.0;
    39.  
    40. //The variable "functionState" controlls which function, "Accell()" or "Slow()", is active. "0" is function "Accell()" and "1" is function "Slow()".
    41. private var functionState = 0;
    42.  
    43. //The next two variables are used to make sure that while the function "Accell()" is running, the function "Slow()" can not run (as well as the reverse).
    44. private var accelState : boolean;
    45. private var slowState : boolean;
    46.  
    47. //This variable will store the "active" target object (the waypoint to move to).
    48. private var waypoint : Transform;
    49.  
    50. //This is the speed the object will rotate to face the active Waypoint.
    51. var rotationDamping = 6.0;
    52.  
    53. //If this is false, the object will rotate instantly toward the Waypoint. If true, you get smoooooth rotation baby!
    54. var smoothRotation = true;
    55.  
    56. //This variable is an array. []< that is an array container if you didnt know. It holds all the Waypoint Objects that you assign in the inspector.
    57. var waypoints : Transform[];
    58.  
    59. //This variable keeps track of which Waypoint Object, in the previously mentioned array variable "waypoints", is currently active.
    60. private var WPindexPointer : int;
    61.  
    62.  
    63.  
    64.  
    65.  
    66. //Functions! They do all the work.
    67. //You can use the built in functions found here: [url]http://unity3d.com/support/documentation/ScriptReference/MonoBehaviour.html[/url]
    68. //Or you can declare your own! The function "Accell()" is one I declared.
    69. //You will want to declare your own functions because theres just certain things that wont work in "Update()". Things like Coroutines: [url]http://unity3d.com/support/documentation/ScriptReference/index.Coroutines_26_Yield.html[/url]
    70.  
    71.  
    72. //The function "Start()" is called just before anything else but only one time.
    73. function Start ()
    74. {
    75.    functionState = 0; //When the script starts set "0" or function Accell() to be active.
    76.      
    77. }
    78.  
    79.  
    80.  
    81.  
    82. //The function "Update()" is called every frame. It can get slow if overused.
    83. function Update ()
    84. {
    85.    if (functionState == 0) //If functionState variable is currently "0" then run "Accell()". Withouth the "if", "Accell()" would run every frame.
    86.    {
    87.       Accell ();
    88.    }
    89.    if (functionState == 1) //If functionState variable is currently "1" then run "Slow()". Withouth the "if", "Slow()" would run every frame.
    90.    {
    91.       Slow ();
    92.    }
    93.    waypoint = waypoints[WPindexPointer]; //Keep the object pointed toward the current Waypoint object.
    94. }
    95.  
    96.  
    97.  
    98.  
    99. //I declared "Accell()".
    100. function Accell ()
    101. {
    102.    if (accelState == false) //
    103.    {                   //
    104.       accelState = true;    //Make sure that if Accell() is running, Slow() can not run.
    105.       slowState = false;    //
    106.    }
    107.                       //
    108. //I grabbed this next part from the unity "SmoothLookAt" script but try to explain more.
    109.    if (waypoint) //If there is a waypoint do the next "if".
    110.    {
    111.       if (smoothRotation) //If smoothRotation is set to "On", do the rotation over time with nice ease in and ease out motion.
    112.       {
    113.          //Look at the active waypoint.
    114.          var rotation = Quaternion.LookRotation(waypoint.position - transform.position);
    115.          //Make the rotation nice and smooth.
    116.          transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * rotationDamping);
    117.       }
    118.    }
    119.    //Now do the accelleration toward the active waypoint untill the "speedLimit" is reached
    120.    currentSpeed = currentSpeed + accel * accel;
    121.    transform.Translate (0,0,Time.deltaTime * currentSpeed);
    122.    
    123.    //When the "speedlimit" is reached or exceeded ...
    124.    if (currentSpeed >= speedLimit)
    125.    {
    126.        // ... turn off accelleration and set "currentSpeed" to be exactly the "speedLimit". Without this, the "currentSpeed will be slightly above "speedLimit"
    127.       currentSpeed = speedLimit;
    128.    }
    129. }
    130.  
    131.  
    132.  
    133.  
    134. //The function "OnTriggerEnter" is called when a collision happens.
    135. function OnTriggerEnter ()
    136. {
    137.    functionState = 1; //When the GameObject collides with the waypoint's collider, activate "Slow()" by setting "functionState" to "1".
    138.    WPindexPointer++;  //When the GameObject collides with the waypoint's collider, change the active waypoint to the next one in the array variable "waypoints".
    139.    
    140.    //When the array variable reaches the end of the list ...
    141.    if (WPindexPointer >= waypoints.Length)
    142.    {
    143.       WPindexPointer = 0; // ... reset the active waypoint to the first object in the array variable "waypoints" and start from the beginning.
    144.    }
    145. }
    146.  
    147.  
    148.  
    149.  
    150. //I declared "Slow()".
    151. function Slow ()
    152. {
    153.    if (slowState == false) //
    154.    {                  //
    155.       accelState = false; //Make sure that if Slow() is running, Accell() can not run.
    156.       slowState = true;   //
    157.    }                  //
    158.    
    159.    //Begin to do the slow down (or speed up if inertia is set above "1.0" in the inspector).
    160.    currentSpeed = currentSpeed * inertia;
    161.    transform.Translate (0,0,Time.deltaTime * currentSpeed);
    162.    
    163.    //When the "minSpeed" is reached or exceeded ...
    164.    if (currentSpeed <= minSpeed)
    165.       {
    166.       currentSpeed = 0.0; // ... Stop the movement by setting "currentSpeed to Zero.
    167.       yield WaitForSeconds (stopTime); //Wait for the amount of time set in "stopTime" before moving to next waypoint.
    168.       functionState = 0; //Activate the function "Accell()" to move to next waypoint.
    169.    }
    170. }
    Code (csharp):
    1.  
    2. var accel = 0.8;
    3. var inertia = 0.9;
    4. var speedLimit = 10.0;
    5. var minSpeed = 1.0;
    6. var stopTime = 1.0;
    7.  
    8. private var currentSpeed = 0.0;
    9.  
    10. private var functionState = 0;
    11. private var accelState : boolean;
    12. private var slowState : boolean;
    13.  
    14. private var waypoint : Transform;
    15. var rotationDamping = 6.0;
    16. var smoothRotation = true;
    17. var waypoints : Transform[];
    18. private var WPindexPointer : int;
    19.  
    20.  
    21. function Start ()
    22. {
    23.     functionState = 0;     
    24. }
    25.  
    26.  
    27. function Update ()
    28. {
    29.     if (functionState == 0)
    30.     {
    31.         Accell ();
    32.     }
    33.     if (functionState == 1)
    34.     {
    35.         Slow ();
    36.     }
    37.     waypoint = waypoints[WPindexPointer];
    38. }
    39.  
    40.  
    41. function Accell ()
    42. {
    43.     if (accelState == false)
    44.     {                        
    45.         accelState = true;   
    46.         slowState = false;   
    47.     }                        
    48.     if (waypoint)
    49.     {
    50.         if (smoothRotation)
    51.         {
    52.             var rotation = Quaternion.LookRotation(waypoint.position - transform.position);
    53.             transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * rotationDamping);
    54.         }
    55.     }
    56.     currentSpeed = currentSpeed + accel * accel;
    57.     transform.Translate (0,0,Time.deltaTime * currentSpeed);
    58.    
    59.     if (currentSpeed >= speedLimit)
    60.     {
    61.         currentSpeed = speedLimit;
    62.     }
    63. }
    64.  
    65.  
    66. function OnTriggerEnter ()
    67. {
    68.     functionState = 1;
    69.     WPindexPointer++;  
    70.    
    71.     if (WPindexPointer >= waypoints.Length)
    72.     {
    73.         WPindexPointer = 0;
    74.     }
    75. }
    76.  
    77.  
    78. function Slow ()
    79. {
    80.     if (slowState == false)
    81.     {                      
    82.         accelState = false;
    83.         slowState = true;  
    84.     }                      
    85.    
    86.     currentSpeed = currentSpeed * inertia;
    87.     transform.Translate (0,0,Time.deltaTime * currentSpeed);
    88.    
    89.     if (currentSpeed <= minSpeed)
    90.         {
    91.         currentSpeed = 0.0;
    92.         yield WaitForSeconds (stopTime);
    93.         functionState = 0;
    94.     }
    95. }
    96.  
     

    Attached Files:

  2. bigkahuna

    bigkahuna

    Joined:
    Apr 30, 2006
    Posts:
    5,434
    One minor point, don't you mean "acceleration" instead of "excelleration"? ;)
     
  3. cherub

    cherub

    Joined:
    Apr 26, 2006
    Posts:
    493
    oh man thanks, yeah its late...fixed.
     
  4. chaoticheartld

    chaoticheartld

    Joined:
    Aug 17, 2009
    Posts:
    141
    Just thought I would tell you excellent work. The script is definitely "super-commented". Even if a beginner is not looking for a way-point system, simply browsing over the script could give them some insight into a bit of scripting logic.

    Considering the "we are pro, everyone else go away" vibe that has been floating around lately, your effort to assist the new members of the community as much as possible is that much more appreciated.

    P.S. I think I might snag the script, myself. I like how you handled a few things in it.
     
    diliupg and dingaling007 like this.
  5. MikezNesh

    MikezNesh

    Joined:
    Jun 18, 2010
    Posts:
    37
    THis script is awesome, Could you make it so it works for 2d games? Like rotating flatly? Thanks.
     
    vraj95soni likes this.
  6. rocket5tim

    rocket5tim

    Joined:
    May 19, 2009
    Posts:
    242
    Thanks for the example, Cherub. There's some interesting stuff in there. I like the simplicity of using OnTriggerEnter to detect when you've reached a waypoint.

    MikezNesh, to make the script work for 2D, change the following lines:

    Code (csharp):
    1. //Look at the active waypoint.
    2.          var rotation = Quaternion.LookRotation(waypoint.position - transform.position);
    3.          //Make the rotation nice and smooth.
    4.          transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * rotationDamping);
    To something like this which will make the character rotate around the Y axis without looking down at the waypoints. (note I didn't test this in Cherub's script)

    Code (csharp):
    1.         // rotate to face target
    2.         newRotation = Quaternion.LookRotation(transform.position - waypoint.position, -Vector3.up);
    3.         newRotation.x = 0;
    4.         newRotation.z = 0;
    5.         smoothRotate = Time.deltaTime * 15;
    6.         transform.rotation = Quaternion.Slerp(transform.rotation, newRotation, smoothRotate);
     
  7. Gamerdad81

    Gamerdad81

    Joined:
    Jul 25, 2010
    Posts:
    23
    Works great thanks alot!
     
  8. herpderpy

    herpderpy

    Joined:
    Mar 9, 2010
    Posts:
    477
    Perfect script! This should be shipped with Unity, it's amazing!
     
  9. Werit

    Werit

    Joined:
    Dec 12, 2010
    Posts:
    38
    Very nice.

    I wonder, could you have it stop (slow down until stop) on a point (or very small sphere)? It would be neat to see logic where it figures out when it should start slowing down so it stops on the point.
     
  10. rockysam888

    rockysam888

    Joined:
    Jul 28, 2009
    Posts:
    650
  11. afalk

    afalk

    Joined:
    Jun 21, 2010
    Posts:
    164
    Nicely commented script :) and THANK you for taking the time to share it!
     
  12. sgtpwnd

    sgtpwnd

    Joined:
    Feb 5, 2012
    Posts:
    2
    i appreciate what you have done here so much and just from this script you have taught me alot... with that said i have a problem. the capsule that i make with a rigid body and sphere collider (not capsule collider) reaches the first way point perfectly...seriously its awe inspiring. however once it gets there it just goes around in a retarded circle help please! not looking for anything more then what you may think is the problem.

    alittle more info... the waypoints (there are 3) are in visible range of eachother (i think)
    all have sphere colliders (set first one up then duplicated)
    the waypoints are empty game objects (dont know why that would hurt anything but hey)
     
  13. sgtpwnd

    sgtpwnd

    Joined:
    Feb 5, 2012
    Posts:
    2


    And i fixed it myself i didnt have the objects is trigger toggled on... i dont believe thats in the steps you had if you wanna add it again thank you so much
     
  14. TehWut

    TehWut

    Joined:
    Jun 18, 2011
    Posts:
    1,577
    Awesome! Wouldn't it be nice if every community script had super commenting like yours ;)
     
  15. roger0

    roger0

    Joined:
    Feb 3, 2012
    Posts:
    1,208
    Hello. I tried the script. When I play the game, the object going to the waypoint (in this case a tank) circles around the first waypoint continously. I switched is trigger on for the object, but it just makes it go toward another waypoint and circle around that one, or just does the same thing. Can someone help?

    Also can anyone make an explanation for a script that just makes a object go to a single waypoint? I want to learn that before learning how to do multiple waypoints.

    Also, when I copy and paste a script, the script comes with numbers at the beginning of each line. I have to delete the numbers in order to get the script to work. I have to do this with any script I find on the forums. Is there a way to copy/paste scripts without numbers in front?

    I know i'm very needy but I want to learn so I can do things!

    thanks
     
  16. Ianicm

    Ianicm

    Joined:
    Feb 26, 2012
    Posts:
    80
    Cherub, Thanks a millions times. This worked perfectly and helped me understand and use Waypoints!
     
  17. Mr Bo

    Mr Bo

    Joined:
    Sep 26, 2012
    Posts:
    2
    Thanks Cherub gr8 script :) i want my prefab to stop when it gets to the last waypoint.Ive changed @ 237: WPindexPointer = 0; to currentSpeed = 0;.......but i receive an error msg when it gets to the 1st of my array....Array index is out of range. What am i doing wrong? thx :p
     
  18. Mikea15

    Mikea15

    Joined:
    Sep 20, 2012
    Posts:
    93
    If anyone wants this in C# ;)

    Code (csharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4.  
    5. public class s_Waypoints : MonoBehaviour
    6. {
    7.     //   This is a very simple waypoint system.
    8.     // Each bit is explained in as much detail as possible for people (like me!) who need every single line explained.
    9.     // As a side note to the inexperienced (like me at the moment!), you can delete the word "private" on any variable to see it in the inspector for debugging.
    10.     // I am sure there are issues with this as is, but it seems to work pretty well as a demonstration.
    11.  
    12.     //STEPS:
    13.     //1. Attach this script to a GameObject with a RidgidBody and a Collider.
    14.     //2. Change the "Size" variable in "Waypoints" to the number of waypoints you want to use.
    15.     //3. Drop your waypoint objects on to the empty variable slots.
    16.     //4. Make sure all your waypoint objects have colliders. (Sphere Collider is best IMO).
    17.     //5. Click the checkbox for "is Trigger" to "On" on the waypoint objects to make them triggers.
    18.     //6. Set the Size (radius for sphere collider) or just Scale for your waypoints.
    19.     //7. Have fun! Try changing variables to get different speeds and such.
    20.  
    21.     // Disclaimer:
    22.     // Extreeme values will start to mess things up.
    23.     // Maybe someone more experienced than me knows how to improve it.
    24.     // Please correct me if any of my comments are incorrect.
    25.  
    26.     // This is the rate of accelleration after the function "Accell()" is called.
    27.     // Higher values will cause the object to reach the "speedLimit" in less time.
    28.     public float accel = 0.8f;
    29.  
    30.     // This is the the amount of velocity retained after the function "Slow()" is called.
    31.     // Lower values cause quicker stops. A value of "1.0" will never stop. Values above "1.0" will speed up.
    32.     public float inertia = 0.9f;
    33.  
    34.     // This is as fast the object is allowed to go.
    35.     public float speedLimit = 10.0f;
    36.  
    37.     // This is the speed that tells the functon "Slow()" when to stop moving the object.
    38.     public float minSpeed = 1.0f;
    39.  
    40.     // This is how long to pause inside "Slow()" before activating the function
    41.     // "Accell()" to start the script again.
    42.     public float stopTime = 1.0f;
    43.  
    44.     // This variable "currentSpeed" is the major player for dealing with velocity.
    45.     // The "currentSpeed" is mutiplied by the variable "accel" to speed up inside the function "accell()".
    46.     // Again, The "currentSpeed" is multiplied by the variable "inertia" to slow
    47.     // things down inside the function "Slow()".
    48.     private float currentSpeed = 0.0f;
    49.  
    50.     // The variable "functionState" controlls which function, "Accell()" or "Slow()",
    51.     // is active. "0" is function "Accell()" and "1" is function "Slow()".
    52.     private float functionState = 0;
    53.  
    54.     // The next two variables are used to make sure that while the function "Accell()" is running,
    55.     // the function "Slow()" can not run (as well as the reverse).
    56.     private bool accelState;
    57.     private bool slowState;
    58.  
    59.     // This variable will store the "active" target object (the waypoint to move to).
    60.     private Transform waypoint;
    61.  
    62.     // This is the speed the object will rotate to face the active Waypoint.
    63.     public float rotationDamping = 6.0f;
    64.  
    65.     // If this is false, the object will rotate instantly toward the Waypoint.
    66.     // If true, you get smoooooth rotation baby!
    67.     public bool smoothRotation = true;
    68.  
    69.     // This variable is an array. []< that is an array container if you didnt know.
    70.     // It holds all the Waypoint Objects that you assign in the inspector.
    71.     public Transform[] waypoints;
    72.  
    73.     // This variable keeps track of which Waypoint Object,
    74.     // in the previously mentioned array variable "waypoints", is currently active.
    75.     private int WPindexPointer;
    76.  
    77.     // Functions! They do all the work.
    78.     // You can use the built in functions found here: [url]http://unity3d.com/support/documentation/ScriptReference/MonoBehaviour.html[/url]
    79.     // Or you can declare your own! The function "Accell()" is one I declared.
    80.     // You will want to declare your own functions because theres just certain things that wont work in "Update()". Things like Coroutines: [url]http://unity3d.com/support/documentation/ScriptReference/index.Coroutines_26_Yield.html[/url]
    81.    
    82.     //The function "Start()" is called just before anything else but only one time.
    83.     void Start( )
    84.     {
    85.         // When the script starts set "0" or function Accell() to be active.
    86.         functionState = 0;
    87.     }
    88.  
    89.     //The function "Update()" is called every frame. It can get slow if overused.
    90.     void Update ()
    91.     {
    92.         // If functionState variable is currently "0" then run "Accell()".
    93.         // Withouth the "if", "Accell()" would run every frame.
    94.         if (functionState == 0)
    95.         {
    96.             Accell();
    97.         }
    98.  
    99.         // If functionState variable is currently "1" then run "Slow()".
    100.         // Withouth the "if", "Slow()" would run every frame.
    101.         if (functionState == 1)
    102.         {
    103.             StartCoroutine(Slow());
    104.         }
    105.  
    106.         waypoint = waypoints[WPindexPointer]; //Keep the object pointed toward the current Waypoint object.
    107.     }
    108.  
    109.     // I declared "Accell()".
    110.     void Accell ()
    111.     {
    112.         if (accelState == false)
    113.         {
    114.             // Make sure that if Accell() is running, Slow() can not run.
    115.             accelState = true;
    116.             slowState = false;
    117.         }
    118.  
    119.         // I grabbed this next part from the unity "SmoothLookAt" script but try to explain more.
    120.         if (waypoint) //If there is a waypoint do the next "if".
    121.         {
    122.             if (smoothRotation)
    123.             {
    124.                 // Look at the active waypoint.
    125.                 var rotation = Quaternion.LookRotation(waypoint.position - transform.position);
    126.  
    127.                 // Make the rotation nice and smooth.
    128.                 // If smoothRotation is set to "On", do the rotation over time
    129.                 // with nice ease in and ease out motion.
    130.                 transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * rotationDamping);
    131.             }
    132.         }
    133.  
    134.         // Now do the accelleration toward the active waypoint untill the "speedLimit" is reached
    135.         currentSpeed = currentSpeed + accel * accel;
    136.         transform.Translate (0,0,Time.deltaTime * currentSpeed);
    137.        
    138.         // When the "speedlimit" is reached or exceeded ...
    139.         if (currentSpeed >= speedLimit)
    140.         {
    141.             // ... turn off accelleration and set "currentSpeed" to be
    142.             // exactly the "speedLimit". Without this, the "currentSpeed
    143.             // will be slightly above "speedLimit"
    144.             currentSpeed = speedLimit;
    145.         }
    146.     }
    147.  
    148.     //The function "OnTriggerEnter" is called when a collision happens.
    149.     void OnTriggerEnter ()
    150.     {
    151.         // When the GameObject collides with the waypoint's collider,
    152.         // activate "Slow()" by setting "functionState" to "1".
    153.         functionState = 1;
    154.  
    155.         // When the GameObject collides with the waypoint's collider,
    156.         // change the active waypoint to the next one in the array variable "waypoints".
    157.         WPindexPointer++;
    158.  
    159.         // When the array variable reaches the end of the list ...
    160.         if (WPindexPointer >= waypoints.Length)
    161.         {
    162.             // ... reset the active waypoint to the first object in the array variable
    163.             // "waypoints" and start from the beginning.
    164.             WPindexPointer = 0;
    165.         }
    166.     }
    167.  
    168.     // I declared "Slow()".
    169.     IEnumerator Slow()
    170.     {
    171.         if (slowState == false) //
    172.         {
    173.             // Make sure that if Slow() is running, Accell() can not run.
    174.             accelState = false;
    175.             slowState = true;
    176.         }
    177.  
    178.         // Begin to do the slow down (or speed up if inertia is set above "1.0" in the inspector).
    179.         currentSpeed = currentSpeed * inertia;
    180.         transform.Translate (0,0,Time.deltaTime * currentSpeed);
    181.        
    182.         // When the "minSpeed" is reached or exceeded ...
    183.         if (currentSpeed <= minSpeed)
    184.         {
    185.             // ... Stop the movement by setting "currentSpeed to Zero.
    186.             currentSpeed = 0.0f;
    187.             // Wait for the amount of time set in "stopTime" before moving to next waypoint.
    188.             yield return new WaitForSeconds(stopTime);
    189.             // Activate the function "Accell()" to move to next waypoint.
    190.             functionState = 0;
    191.         }
    192.     }
    193.  
    194. }
    195.  
    196.  
     
  19. CrazySi

    CrazySi

    Joined:
    Jun 23, 2011
    Posts:
    538
    Class s_Waypoints? The OO style police won't be happy about that!
     
  20. airesdav

    airesdav

    Joined:
    Nov 13, 2012
    Posts:
    128
    does this code get attached to the enemy I am not sure where this is supposed to go can someone help
     
  21. Berenger

    Berenger

    Joined:
    Jul 11, 2012
    Posts:
    78
    Just for the information, unless you add a rigidbody on the gameobject with that script, it won't go pass the first waypoint as collisions won't be registered. Don't forget to disable gravity, enable isKinematic and make sure the colliders are triggers.
     
  22. Juhsi

    Juhsi

    Joined:
    Apr 27, 2013
    Posts:
    1
    I'm excited to find this code and use immediately,but I got some problem about it :(

    I was attach script to my animation(bone&model) and just get model a collider and rigidbody,then I put my waypoint into script,but my animation didnt walk through the waypoint,it just stop at place.

    There have a video about my question: https://www.dropbox.com/s/tlp94sfbmcsnosr/bandicam%202013-05-01%2004-13-37-210.avi

    Could anyone help me? Thank you very much!
     
    Last edited: Apr 30, 2013
  23. hike1

    hike1

    Joined:
    Sep 6, 2009
    Posts:
    401
    quote
    my animation didnt walk through the waypoint,it just stop at place.
    unquote

    I attached this to an animated horse, he moves through the waypoints, he doesn't animate though, reminds me of Pokey, Gumby's pal.
     
  24. pabloromocl

    pabloromocl

    Joined:
    Jan 11, 2013
    Posts:
    3
    This script is working great.

    I didn't need anything more than a linear path with 4 waypoints and it didn't need at all dynamic path find so this works great for me.

    Greetings and nice work
     
  25. Hamsterp

    Hamsterp

    Joined:
    Dec 13, 2013
    Posts:
    1
    This is awesome, thank you for the clean coding. Needed a simple waypoint script for my 2D top down game, with minor changes this will do the trick.

    This is why I love unity community.

    @Mikea15 thank you too!
     
  26. NutellaDaddy

    NutellaDaddy

    Joined:
    Oct 22, 2013
    Posts:
    288
    It's all in Javascript. What would you use for the functionState variable in C#? A Boo, int......what?
     
  27. cherub

    cherub

    Joined:
    Apr 26, 2006
    Posts:
    493
    public int functionState = 0;
     
  28. sangocreator

    sangocreator

    Joined:
    Oct 16, 2012
    Posts:
    9
    I commented out the:
    if (accelState == false)
    {
    accelState = true;
    slowState = false;
    }

    and the:

    if (accelState == false)
    {
    accelState = true;
    slowState = false;
    }

    and this had no effect so I think they can be removed as they do not interact with any other part of the code. However, this was a great bit of work you did and helped me understand better how to code in Unity . Many thanks for your hard work and thoughtfulness. :D
     
  29. BobIsHereToPlay

    BobIsHereToPlay

    Joined:
    Apr 6, 2013
    Posts:
    1
    I would like it to fully facing the enemy, then only starts moving to other waypoint. Can someone teach me that?
     
  30. filip0258

    filip0258

    Joined:
    Mar 12, 2014
    Posts:
    1
    :O for me car goes to 3 waypoint and then he rotate helppp
     
  31. Deleted User

    Deleted User

    Guest

    Great script, thanks! Assigning transforms using the waypoints array is just what I was looking for. Now, I can assign any transform in my scene to be a waypoint. You can see my results here. Thanks again.
     
  32. rockysam888

    rockysam888

    Joined:
    Jul 28, 2009
    Posts:
    650
    Thank you.
     
  33. Hard target

    Hard target

    Joined:
    Oct 31, 2013
    Posts:
    132
    what this needs is a way to drop the waypoints to the ground.
     
  34. Troas

    Troas

    Joined:
    Jan 26, 2013
    Posts:
    157

    Actually it doesn't, it's very simple already just make an empty game object with sphere collider attached, check the "is trigger" box place it in the component area for the waypoints and away you go.

    Unless I've completely read the script instructions wrong.
     
  35. Hard target

    Hard target

    Joined:
    Oct 31, 2013
    Posts:
    132
    I named my waypoints waypoint1,waypoint,2,waypoint3,waypoint4,waypoint5,waypoint6 and gave them a sphere collider.And put is trigger on them.And i set the size variable to six.And my sphere won't go to all the waypoints.Does anyone know a solution?
     
  36. Hard target

    Hard target

    Joined:
    Oct 31, 2013
    Posts:
    132
    I had to pull the parented waypoints above the ground.Then it worked.
     
  37. Troas

    Troas

    Joined:
    Jan 26, 2013
    Posts:
    157
    You have to drag and drop those waypoints into the waypoint array you set to a size of 6. Then you have to attach that script to the object that you want to follow them. Again go look at the tutorials I posted for you those literally explain all of this to you instead of us having to walk you through it.
     
  38. habsi70

    habsi70

    Joined:
    Jan 30, 2013
    Posts:
    25
    Very nice Script, thank you for the work!
     
  39. cherub

    cherub

    Joined:
    Apr 26, 2006
    Posts:
    493
    Super happy this thread is still alive!
     
  40. OmniForge

    OmniForge

    Joined:
    Apr 29, 2014
    Posts:
    6
    quick question regarding the currentSpeed and speedLimit variables in the Accel() function;
    Code (JavaScript):
    1.    //Now do the accelleration toward the active waypoint untill the "speedLimit" is reached
    2.    currentSpeed = currentSpeed + accel * accel;
    3.    transform.Translate (0,0,Time.deltaTime * currentSpeed);
    4.  
    5.    //When the "speedlimit" is reached or exceeded ...
    6.    if (currentSpeed >= speedLimit)
    7.    {
    8.        // ... turn off accelleration and set "currentSpeed" to be exactly the "speedLimit". Without this, the "currentSpeed will be slightly above "speedLimit"
    9.       currentSpeed = speedLimit;
    10.    }
    now, the way I'm reading this says that the current speed is always added onto to by the accel^2, then it is applied to the transform and AFTERWARDS the currentSpeed is then restricted to the speedLimit. Shouldn't this apply in a different order? Such that the speedLimit is decided upon before it is applied to the transform? In this fashion:
    Code (JavaScript):
    1.    //Now do the accelleration toward the active waypoint untill the "speedLimit" is reached
    2.    currentSpeed = currentSpeed + accel * accel;
    3.  
    4.    //When the "speedlimit" is reached or exceeded ...
    5.    if (currentSpeed >= speedLimit)
    6.    {
    7.        // ... turn off accelleration and set "currentSpeed" to be exactly the "speedLimit". Without this, the "currentSpeed will be slightly above "speedLimit"
    8.       currentSpeed = speedLimit;
    9.    }
    10.  
    11.    transform.Translate (0,0,Time.deltaTime * currentSpeed);
    in this way we can ensure that the speed limit number itself is adhered to, rather than one calculation past it?
     
  41. rizqiaws

    rizqiaws

    Joined:
    Sep 5, 2014
    Posts:
    8
    WOW, it's cool waypoints script ;)
    could you show me how to create waypoints on mouse click?
    I think I have no idea :(
    please help :)
     
  42. cherub

    cherub

    Joined:
    Apr 26, 2006
    Posts:
    493
    Yes OmniForge :) I wrote this a very long time ago.
     
  43. BryanO

    BryanO

    Joined:
    Jan 8, 2014
    Posts:
    186
    Has this been updated to include the nav mesh?
     
  44. Simigla

    Simigla

    Joined:
    Aug 20, 2015
    Posts:
    4
    guys and what is this? so what i did so far is that :
    1.I put a gameobject (spider) into the scene. put the waypoint script to it, a box collider and a rigid body with no gravity and kinematic on. i set the scrpt waypoint size to 3
    2. i put 3 waypoint to the ground with a sphere collider on them.
    and thats all. because the script said this.
    and the thing i got is:
    my spider went to the first waypoint than it started to fly away from the scene for no reason! what did i do wrong?
     
  45. Marcos-Elias

    Marcos-Elias

    Joined:
    Nov 1, 2014
    Posts:
    159
    Hey, I'm sorry for replying to an old thread... But I think it is very important to give proper credits :D

    I'm using your code in my project that will be open source. I was making an AI system with physics and wheelcolliders, but that is bad if you have lots of cars. So I found this topic with this amazing code!

    My basic change is that... AI will always go forward, unless it finds a waypoint which tells what the next waypoint is. On the last waypoint it goes forward... And so on. The final results are amazing!



    If you like it, please check here:

    http://forum.unity3d.com/threads/op...stem-that-really-works-out-of-the-box.388605/

    For this movement script I'll put the credits at the begining of the file to this thread. Of course my AI system has lots of my own scripts, but for the basic waypoint, I think this is one of the best!
     
  46. KENNYBERG

    KENNYBERG

    Joined:
    Feb 18, 2016
    Posts:
    2
    thanks for taking the time and being that guy that is trying to better this community like a flaming beacon of hope burning down the snobbery that are pro developers who's nostrils flare at the meer mentions of a noob in peril. uhh yeah thanks for being awesome and helping us beginners

    i have a question
    i have an enemy that will follow my player when i get in a certain range of him and have this script attached:

    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    using UnityEngine;
    using System.Collections;

    public class Chase : MonoBehaviour {

    public Transform player;
    public Animator anim;

    // Use this for initialization
    void Start ()
    {
    anim = GetComponent<Animator>();
    }

    // Update is called once per frame
    void Update ()
    {

    if (Vector3.Distance (player.position, this.transform.position) < 10) {
    Vector3 direction = player.position - this.transform.position;
    direction.y = 0;

    this.transform.rotation = Quaternion.Slerp (this.transform.rotation,
    Quaternion.LookRotation (direction), 0.3f);

    anim.SetBool("isIdle",false);
    if (direction.magnitude > 5)
    {
    this.transform.Translate (0, 0, 0.3f);
    anim.SetBool("isInflight",true);
    anim.SetBool("isShooting",false);

    }
    else
    {
    anim.SetBool("isShooting",true);
    anim.SetBool("isInflight",false);
    }

    }
    else
    {
    anim.SetBool("isIdle",true);
    anim.SetBool("isInflight",false);
    anim.SetBool("isShooting",false);


    }

    }
    }

    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    sorry so noobish dont ven know how to add code to a comment lol

    when i attach your script some crazy behaviour takes place. is there a way for me to have my enemy return to his original position after he chases me someone suggested a golpos. with a waypoint and thats what brought me here. but i will be using this on other objects
    thanks again and hope you can or even have an answer soon
     
  47. Adam-Buckner

    Adam-Buckner

    Joined:
    Jun 27, 2007
    Posts:
    5,664
    Don't forget this is an old thread and may be obsolete.

    If you do post code, can you please use code tags:

    http://forum.unity3d.com/threads/using-code-tags-properly.143875/
     
  48. PVisser

    PVisser

    Joined:
    Apr 24, 2014
    Posts:
    61
    I just used this code for a script (C#) and as far as I can tell it does exactly what it needs to do, make an object follow waypoints. The object sometimes stops at a waypoint as if it is thinking, which I find kind of interesting because it makes the object look sentient.

    Anyhow, I just came here to say thank you for the script. :)
     
  49. Bduarte

    Bduarte

    Joined:
    Jul 17, 2015
    Posts:
    2
    I tried to use this script for a 2D game I am working on. I am also complete noob. I made the changes recommended by rocket5tim. However my NPC doesn't go towards the first waypoint. She just goes to the right and then she spins around the Z axis going in and out of the map. I also have a dialog box that is activated when the player enters a 2D collider around the NPC. I've tried deactivating this collider to see if it is causing problems but it doesn't seem like it is causing problems. If anybody has any solutions or advice that might help I would deeply appreciate it. Thank you.
     
  50. Siraaaj-Ahmed

    Siraaaj-Ahmed

    Joined:
    Oct 30, 2016
    Posts:
    1
    Thank you guys so much. This is awesome. I needed a way to make a big wasp swoop down at the character and fly around and come back. This seems like a really good way to achieve that. Thanks again! :D