• 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 ObiBrenBenobi · Dec 11, 2017 at 08:40 AM · transformtrigger

How to make enemies moving in a line oscillate between going left and going right at a certain trigger,How to make one enemy go left at a certain point and the following right

Hey guys,
this is the code I am having trouble with...
I am trying to build a TD game in which, as usual, multiple enemies of the same kind spawn and make their way to the finish line. I am trying to make one enemy go left, the next one right and then oscillate between the two, but instead once they all go into the same direction and they start to rapidly oscillate right at the exit going left, right, left, right etc...
Now, how would I go about this the correct way? because this is clearly not working...

 public class Enemy_Movement_Normal_Speed : MonoBehaviour
 {
     public float moveSpeed = 2f;
     public bool changeDir1;
     public bool changeDirleft;
     public Transform changeDir2;
     public int changeDirectionDir1 = 1;
     

     void FixedUpdate()
     {
         Vector3 vel = transform.forward * moveSpeed;    //move forward
         vel.y = GetComponent<Rigidbody>().velocity.y;
         GetComponent<Rigidbody>().velocity = vel;

         if (changeDir1 == true && changeDirectionDir1 == 1) //move right at the junction
         {
             Vector3 vel2 = transform.right * moveSpeed;
             vel2.y = GetComponent<Rigidbody>().velocity.y;
             GetComponent<Rigidbody>().velocity = vel2;

          
             //transform.LookAt(changeDir2)

             Debug.Log(changeDirectionDir1);
         }
         if (changeDir1 == true && changeDirectionDir1 == 2) //move left at the junction
         {
             Vector3 vel2 = -transform.right * moveSpeed;
             vel2.y = GetComponent<Rigidbody>().velocity.y;
             GetComponent<Rigidbody>().velocity = vel2;


             //transform.LookAt(changeDir2)

             Debug.Log(changeDirectionDir1);
         }
         if (changeDirleft == true)  //move foward at different junction again, 
                                     //called left because it
                                     //is like actually moving left, in game 
                                    //world however it's forward
         {
             Vector3 vel2 = transform.forward * moveSpeed;
             vel2.y = GetComponent<Rigidbody>().velocity.y;
             GetComponent<Rigidbody>().velocity = vel2; 
         }
     }
     public void OnTriggerEnter(Collider other)
     {
         if (other.CompareTag("Change Dir 1")) //is the enemy at the first junction?
         {
             changeDir1 = true;
             changeDirectionDir1 += 1;   //this is supposed to go up once when they enter
                                         // the trigger in order for the next one to move left
             Debug.Log("Entered the first trigger");
         }
         if (other.CompareTag("Change Dir Left"))
         {
             changeDir1 = false;
             changeDirleft = true;
             Debug.Log("Entered the second trigger");
         }
     }
     public void OnTriggerExit(Collider other)
     {
         if (other.CompareTag("Change Dir 1"))
         {
             changeDirectionDir1 -= 1; //subtract one again so that 
                  //once one has left the junction the next one goes right again
         }
     }
 }

Sorry for the messy code, I am still a beginner ^^

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
1

Answer by tcjulian · Dec 11, 2017 at 09:43 AM

Based on your code, I'm assuming that each enemy will have its own copy of this script, which means that each will have its own instance variables (see https://en.wikipedia.org/wiki/Instance_variable).


Instead, what you probably want is to have a single variable associated with each trigger zone that causes a direction change. In a Tower Defense game, I would probably have a single script that keeps track of and controls all enemies rather than making each enemy be in charge of its own movement, because that will help coordinate their movements at a high level. That manager script would have references to each enemy and each trigger, and when an enemy enters a trigger zone, the manager could ask the trigger which direction the enemy should go and tell the trigger that an enemy has reached it. The trigger could then update a variable that will make it respond with a different direction when the manager detects that the next enemy has reached it.


If you'd prefer to keep having enemies manage their own movement, you could make a new TriggerZone MonoBehaviour that keeps track of and updates the next desired enemy direction. Something like this:

 public class TriggerZone : MonoBehaviour {
    private float _enemyDirection = 1f;
    public float GetNextEnemyDirectionAndUpdate () {
       float nextDir = _enemyDirection;
       _enemyDirection = -_enemyDirection;
      return nextDir;
    }
 }
 
 public class Enemy_Movement_Normal_Speed : MonoBehaviour {
    private float _myDirection = 1f;

    void FixedUpdate () {
        // ... Move base on _myDirection
    }   

    void OnTriggerEnter (Collider other) {
       TriggerZone zone = other.GetComponent<TriggerZone>();
       if (zone != null) {
          _myDirection = zone.GetNextEnemyDirectionAndUpdate();
       }
    }
 }

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 ObiBrenBenobi · Dec 11, 2017 at 09:50 AM 0
Share

I think I understand xD

I'll try to write something along the line of what you have suggested rather than have every enemy do it's own "path finding". Should also make it easier for me to control.

Thanks :)

avatar image tcjulian ObiBrenBenobi · Dec 11, 2017 at 10:10 AM 1
Share

You're welcome! If you do end up going in that direction, you might want to consider having the manager use something like https://docs.unity3d.com/ScriptReference/Physics.OverlapSphereNonAlloc.html to see if an enemy is within a trigger zone ins$$anonymous$$d of OnTriggerEnter

Good luck :)

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

101 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 avatar image

Related Questions

transform.position not executed with OnTrigger2D 1 Answer

What would you do with essential items? 1 Answer

Transform to a random height 0 Answers

TriggerExit not working as intended/Transforming GameObject Problems 0 Answers

Trigger collision detection problem 0 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