Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 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 /
avatar image
0
Question by Ulftek · Feb 25, 2019 at 08:13 PM · timers

Need help with enemy stop and go movement

I've been wrestling with this for a while now, and something just isn't clicking for me. I'm working on developing some behaviors for some enemies in a top-down 2D RPG. Right now I'm trying to create a script that will have enemies move in a random direction for a certain duration, stop for a certain duration, then pick a new random direction, move, then stop, then move, etc. I'm not sure what to do here. I've been trying to get two timers to work together with no success. I might be missing something simple, but for whatever reason, I'm not seeing it. Getting the enemies to move and change direction isn't the hard part. I found some code online that helps with that (although I might change it to move just left, right, up, and down). I just can't figure out how to get a pause to work. I've tried using other timers and even tried a coroutine without success. As a starting point, here is the code I found online. Any help will be GREATLY appreciated. I get the feeling I might just need a nudge to get everything to fall into place in my head.

 private float latestDirectionChangeTime;
     private readonly float directionChangeTime = 3f;
     private float characterVelocity = 2f;
     private Vector2 movementDirection;
     private Vector2 movementPerSecond;
 
 
     void Start()
     {
         latestDirectionChangeTime = 0f;
         calcuateNewMovementVector();
     }
 
     void calcuateNewMovementVector()
     {
         //create a random direction vector with the magnitude of 1, later multiply it with the velocity of the enemy
         movementDirection = new Vector2(Random.Range(-1.0f, 1.0f), Random.Range(-1.0f, 1.0f)).normalized;
         movementPerSecond = movementDirection * characterVelocity;
     }
 
     void Update()
     {
         //if the changeTime was reached, calculate a new movement vector
         if (Time.time - latestDirectionChangeTime > directionChangeTime)
         {
             latestDirectionChangeTime = Time.time;
             calcuateNewMovementVector();
         }
 
         //move enemy: 
         transform.position = new Vector2(transform.position.x + (movementPerSecond.x * Time.deltaTime),
         transform.position.y + (movementPerSecond.y * Time.deltaTime));
 
     }
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

2 Replies

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

Answer by Tsaras · Feb 25, 2019 at 08:38 PM

You can use a boolean flag to set this up. The code might be something like this (not tested):

 float moveDuration;
 float pauseDuration;
 float timer;
 bool paused;
 
 void Start(){
     timer = moveDuration;    //to get it moving from the start
     paused = false;
 }
 
 void Update(){
     timer -= Time.deltaTime;
     if (timer <=0){
         if (paused){
             timer = moveDuration;
             FindNewDirection();
             paused = false;
         } else {
             timer = pauseDuration;
             paused = true;
         }
         
         return;
     }
     
     if (!paused){
         //move character here
     }
 }

Comment
Add comment · Show 2 · 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 Ulftek · Feb 26, 2019 at 12:10 AM 0
Share

I got your code to work. Thank you! I'm going to study it so I can better understand it and not just use it. Doing this sort of thing has always been an obstacle for me and I need to get past it. Here is my implementation (although I will most likely tweak it as necessary once I understand it better). Again, thank you!

 public float moveDuration = 1f;
     public float pauseDuration = 2f;
     private float timer;
     private bool paused;
     private Vector2 movementDirection;
     private Vector2 movementPerSecond;
     private float characterVelocity = 2f;
 
     protected override void Start()
     {
         timer = moveDuration;    //to get it moving from the start
         paused = false;
     }
 
     protected override void Update()
     {
         timer -= Time.deltaTime;
         if (timer <= 0)
         {
             if (paused)
             {
                 timer = moveDuration;
                 CalcuateNew$$anonymous$$ovementVector();
                 paused = false;
             }
             else
             {
                 timer = pauseDuration;
                 paused = true;
             }
 
             return;
         }
 
         if (!paused)
         {
             transform.position = new Vector2(transform.position.x + (movementPerSecond.x * Time.deltaTime),
         transform.position.y + (movementPerSecond.y * Time.deltaTime));
         }
     }
 
     void CalcuateNew$$anonymous$$ovementVector()
     {
         //create a random direction vector with the magnitude of 1, later multiply it with the velocity of the enemy
         movementDirection = new Vector2(Random.Range(-1.0f, 1.0f), Random.Range(-1.0f, 1.0f)).normalized;
         movementPerSecond = movementDirection * characterVelocity;
     }
avatar image Tsaras Ulftek · Feb 26, 2019 at 04:19 PM 0
Share

Glad I helped. The basis is the paused flag toggling between true and false to change between the move and pause states of the enemy when the timer has counted down the appropriate time. Then only when paused is false it moves. You can even remove the return; statement.

avatar image
0

Answer by xxmariofer · Feb 25, 2019 at 08:30 PM

well here is the easiest way to achieve this without touching much of the code, override the start and update method and add theInvokIsWaiting one.

  private bool isWaiting;

  void Start()
  {
      isWaiting = false;
      latestDirectionChangeTime = 0f;
      calcuateNewMovementVector();
  }

  void InvokeIsWaiting()
  {
       latestDirectionChangeTime = Time.time;
       isWaiting = false;
  }
  void Update()
  {
      //if the changeTime was reached, calculate a new movement vector
      if (Time.time - latestDirectionChangeTime > directionChangeTime && !isWaiting)
      {
          isWaiting = true;
          calcuateNewMovementVector();
          Invoke("InvokeIsWaiting", 4) //will wait for 4 seconds this is just an example use your desired value
      }
 
      //move enemy: 
      transform.position = new Vector2(transform.position.x + (movementPerSecond.x * Time.deltaTime),
      transform.position.y + (movementPerSecond.y * Time.deltaTime));
 
  }
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 Ulftek · Feb 26, 2019 at 12:05 AM 0
Share

I tried this, but couldn't get it to work. The enemy just changes direction after a certain duration without a pause in between. Any ideas what I did wrong?

 public float waitTime = 2f;
     public float directionChangeTime = 3f;
 
     private float latestDirectionChangeTime;
     private float characterVelocity = 2f;
     private Vector2 movementDirection;
     private Vector2 movementPerSecond;
     private bool isWaiting;
 
     protected override void Start()
     {
         isWaiting = false;
         latestDirectionChangeTime = 0f;
         CalcuateNew$$anonymous$$ovementVector();
     }
 
     protected override void Update()
     {
         //if the changeTime was reached, calculate a new movement vector
         if (Time.time - latestDirectionChangeTime > directionChangeTime && !isWaiting)
         {
             isWaiting = true;
             CalcuateNew$$anonymous$$ovementVector();
             Invoke("InvokeIsWaiting", waitTime);
         }
 
         //move enemy: 
         transform.position = new Vector2(transform.position.x + (movementPerSecond.x * Time.deltaTime),
         transform.position.y + (movementPerSecond.y * Time.deltaTime));
 
     }
 
     void InvokeIsWaiting()
     {
         latestDirectionChangeTime = Time.time;
         isWaiting = false;
     }
 
     void CalcuateNew$$anonymous$$ovementVector()
     {
         //create a random direction vector with the magnitude of 1, later multiply it with the velocity of the enemy
         movementDirection = new Vector2(Random.Range(-1.0f, 1.0f), Random.Range(-1.0f, 1.0f)).normalized;
         movementPerSecond = movementDirection * characterVelocity;
     }
avatar image xxmariofer Ulftek · Feb 26, 2019 at 12:20 AM 0
Share

i did it fast and couldnt test it, i know you already found a solution but here is a tested working one

 public float waitTime = 2f;
 public float directionChangeTime = 3f;

 private float latestDirectionChangeTime;
 private float characterVelocity = 2f;
 private Vector2 movementDirection;
 private Vector2 movementPerSecond;
 private bool isWaiting;

 protected void Start()
 {
     isWaiting = false;
     latestDirectionChangeTime = 0f;
     CalcuateNew$$anonymous$$ovementVector();
 }

 protected void Update()
 {
     //if the changeTime was reached, calculate a new movement vector
     if (Time.time - latestDirectionChangeTime > directionChangeTime && !isWaiting)
     {
         isWaiting = true;
         Invoke("InvokeIsWaiting", waitTime);
         movementPerSecond = Vector3.zero;
     }

     //move enemy: 
     transform.position = new Vector2(transform.position.x + (movementPerSecond.x * Time.deltaTime),
     transform.position.y + (movementPerSecond.y * Time.deltaTime));

 }

 void InvokeIsWaiting()
 {
     latestDirectionChangeTime = Time.time;
     CalcuateNew$$anonymous$$ovementVector();
     isWaiting = false;
 }

 void CalcuateNew$$anonymous$$ovementVector()
 {
     //create a random direction vector with the magnitude of 1, later multiply it with the velocity of the enemy
     movementDirection = new Vector2(UnityEngine.Random.Range(-1.0f, 1.0f), UnityEngine.Random.Range(-1.0f, 1.0f)).normalized;
     movementPerSecond = movementDirection * characterVelocity;
 }
avatar image Ulftek xxmariofer · Feb 26, 2019 at 01:35 AM 0
Share

I got yours to work, too :). Thank you! Going to post another question about keeping these randomly moving enemies confined to a specific area if you are interested :).

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

100 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 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 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

Timescale and Timers - what am I doing wrong? 1 Answer

Unity 5 - Time counter Up script (millisecond precision) UI 1 Answer

Timers, LoadLevel 3 Answers

How do I synchronise different objects turning on and off? 1 Answer

Increase as timer decreases 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