• 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 Rembo4Fight · Mar 05, 2017 at 03:30 PM · 2dscripting problem2d gamewaitforseconds

Enemy Patrol Wait Time

Hi, I'm looking for create an Enemy Patrol AI script

alt text

And I want to make him to Stop for several seconds on the edge of the platform or when he is detect the wall in front of him So I made the wall and edge detection check for him and he's moving quiet right. Check it in my video.

Enemy walking video on youtube

But I want to make him wait and stay for couple seconds in the moment when he detect the edge or wall I tried the WaitForSecond method but i'm not quiet sure how it works and made the float "Enemy Wait Time"

If you can please help me to solve this! :)

Here is the Code

 using UnityEngine;
 using System.Collections;
 
 public class EnemyPatrol : MonoBehaviour {
 
     public float moveSpeed;
     public bool moveRight;
 
     public Transform wallCheck;
     public float wallCheckRadius;
     public LayerMask whatIsWall;
     private bool hittingWall;
 
     private bool notAtEdge;
     public Transform edgeCheck;
 
     public float enemyWaitTime;
 
     void Start () 
     {
         
     }
         
     void Update () {
 
         hittingWall = Physics2D.OverlapCircle (wallCheck.position, wallCheckRadius, whatIsWall);
 
         notAtEdge = Physics2D.OverlapCircle (edgeCheck.position, wallCheckRadius, whatIsWall);
 
         if(hittingWall || !notAtEdge)
             moveRight = !moveRight;
         
         if (moveRight) 
         { 
             transform.localScale = new Vector3 (0.75f, 0.75f, 1f);
             GetComponent<Rigidbody2D>().velocity = new Vector2(moveSpeed, GetComponent<Rigidbody2D>().velocity.y);
         } else {
             transform.localScale = new Vector3 (-0.75f, 0.75f, 1f);
             GetComponent<Rigidbody2D>().velocity = new Vector2(-moveSpeed, GetComponent<Rigidbody2D>().velocity.y);
         }
     }
 
     IEnumerator WaitTime() {
         moveSpeed = 0;
         yield return new WaitForSeconds (enemyWaitTime);
         yield return 0;
     }
 }
 




screen-shot-2017-03-03-at-145517.png (162.9 kB)
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
2
Best Answer

Answer by ExtinctSpecie · Mar 06, 2017 at 10:12 PM

 float timer = 0.5f;
 if(hittingWall)
 {
     if(timer>0)
     {
         timer -= Time.deltaTime;
         return;
     }
     timer = 0.5f;
 }
 //we reset the timer again notice that this will execute only when hittingWall = true
 //so we reset the timer and it counts down again when hittingWall = true
 
 
Comment
Add comment · Show 4 · 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 Rembo4Fight · Mar 06, 2017 at 10:25 PM 0
Share

Do I add the code right? Enemy spin very fast now

 public float timer = 0.5f;
 
     public float enemyWaitTime;
 
     void Start () 
     {
         
     }
         
     void Update () {
 
         hittingWall = Physics2D.OverlapCircle (wallCheck.position, wallCheckRadius, whatIsWall);
 
         notAtEdge = Physics2D.OverlapCircle (edgeCheck.position, edgeCheckRadius, whatIsWall);
 
         if (hittingWall || !notAtEdge) 
         {
             if (timer > 0) 
             {
                 timer -= Time.deltaTime;
                 return;
             }
             timer = 0.5f;
         }
             
             moveRight = !moveRight;
avatar image ExtinctSpecie · Mar 07, 2017 at 09:29 AM 0
Share
         if (hittingWall || !notAtEdge) 
         {            
             if (timer > 0) 
             {
                 timer -= Time.deltaTime;
                 return;
             }
             moveRight = !moveRight;
             timer = 0.5f;
         }//put the moveRight = !moveRight inside if so the player can swap when he hits a wall and 0.5 seconds have passed
avatar image Rembo4Fight · Mar 08, 2017 at 03:28 PM 0
Share

Thank you very much! It work's

avatar image Rembo4Fight Rembo4Fight · Mar 09, 2017 at 01:03 PM 0
Share

Can you please help with the Speed on this script? I want to make that animation transition which is working on speed But how can i make here that speed is go machimatically to 0 and backwards to my parameter when the enemy is waiting? How to make Timer set the Speed smoothly to 0 and backward? PLEASE if you know how, help me on this one!

avatar image
1

Answer by jwulf · Mar 07, 2017 at 11:24 AM

You never call WaitTime(), do you?

You should update this

      if(hittingWall || !notAtEdge)
          moveRight = !moveRight;

to

      if(hittingWall || !notAtEdge) {
          moveRight = !moveRight;
          StartCoroutine(WaitTime());
      }

Further introduce a bool "moving" somewhere in the class:

 private bool moving = true; // defaults to true, so the enemy moves at the beginning

And change WaitTime() to:

  IEnumerator WaitTime() {
      moving = false;
      yield return new WaitForSeconds (enemyWaitTime);
      moving = true;
  }

And at the start of Update():

 void Udate() {
     if(!moving)
         return;
 } 

, so the enemy doesn't move when moving == false.

There are some other things I would suggest to change in your code, but only to name the most importent: Calling GetComponent() in Update() (i.e. every frame) several times is not a good idea. You should rather make the rigidBody a member variable and introduce an Awake()-Method...

 RigidBody2D rb;
 void Awake() {
     rb = GetComponent<RigidBody2D>();
 }

... and then, whenever you want to change something on the RigidBody2D, you just call

 rb.velocity = ...; // or whatever

.

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 Rembo4Fight · Mar 08, 2017 at 03:30 PM 0
Share

Thank you very much Your answer is working too but it happened after 0.5f after detecting, not immediately)thank you

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

The best place to ask and answer questions about development with Unity.

To help users navigate the site we have posted a site navigation guide.

If you are a new user to Unity Answers, check out our FAQ for more information.

Make sure to check out our Knowledge Base for commonly asked Unity questions.

If you are a moderator, see our Moderator Guidelines page.

We are making improvements to UA, see the list of changes.



Follow this Question

Answers Answers and Comments

4 People are following this question.

avatar image avatar image avatar image avatar image

Related Questions

Destroy script turns objects into ghosts 2 Answers

2D Top Down SmokeBomb 0 Answers

Mouse Click Walk to Idle Animations 0 Answers

Trying to get gameobject to point to mouse in a orbit around the player 2D 1 Answer

My character won't stop crouching, they dont stop crouching. Here is the code: 2 Answers


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