Unity2D: Move enemy towards object when spotted












0















I have a script that will make enemies look around an area for random objects within a scene, if the enemy spots the object then the enemy will move forward. However, this is not what I want the enemy to do, instead of the enemy moving forward, I want the enemy to move towards the object and then once the enemy reaches the object, I want the enemy to stop it's movement. I have different types of objects with different tags attached to it so I don't think moving the object using the object's tag name will be effective. I hope to find a way to move the enemies to the nearest object using the object's Layer name as all of my objects have the same layer name, meaning whatever object is spawn in to the scene the enemy will be able to move towards it. Is there a way to move my enemy towards an object when they have the object in sight? Thank you for your help!



This is my code so far:



public Transform sightStart, sightEnd, sightStart2, sightEnd2;

public Vector3 direction = Vector3.right;
public Vector3 direction2 = Vector3.right;

public float speed = 2f;

public bool spotted = false;
public bool rotate, moveEnemy = false;

public Camera mainCam;

public GameObject EndSight, EndSight2;

void Start () {
speed = 2f;
spotted = false;
rotate = false;
moveEnemy = false;
mainCam = GameObject.Find ("Main Camera").GetComponent<Camera> ();

}


void Update () {
Behaviours ();
if (mainCam.WorldToScreenPoint (this.transform.position).x > Screen.width / 2) {
direction.x = -1;
InvokeRepeating ("EnemySight", 0, 10f);
if (moveEnemy == false) {
RayCasting ();
Destroy (gameObject, 7f);
}
} else {
direction.x = 1;
InvokeRepeating ("EnemySight", 0, 10f);
if (moveEnemy == false) {
RayCasting2 ();
Destroy (gameObject, 7f);
}
}
}

void EnemySight() {
if (rotate == false) {
if (mainCam.WorldToScreenPoint (this.transform.position).x > Screen.width / 2) {
EndSight.transform.Translate (direction2 * speed * Time.deltaTime);
direction2.x = 0;
direction2.y = 1;
StartCoroutine (wait1 ());
} else {
EndSight2.transform.Translate (direction2 * speed * Time.deltaTime);
direction2.x = 0;
direction2.y = 1;
StartCoroutine (wait1 ());

}
} else if (rotate == true) {
if (mainCam.WorldToScreenPoint (this.transform.position).x > Screen.width / 2) {
EndSight.transform.Translate (direction2 * speed * Time.deltaTime);
direction2.x = 0;
direction2.y = -1;
StartCoroutine (wait2 ());
} else {
EndSight2.transform.Translate (direction2 * speed * Time.deltaTime);
direction2.x = 0;
direction2.y = -1;
StartCoroutine (wait2 ());
}
}
}

IEnumerator wait1() {
yield return new WaitForSeconds (0.7f);
rotate = true;
}

IEnumerator wait2() {
yield return new WaitForSeconds (0.7f);
rotate = false;
}

void RayCasting()
{
Debug.DrawLine (sightStart.position, sightEnd.position, Color.black);
spotted = Physics2D.Linecast (sightStart.position, sightEnd.position, 1 << LayerMask.NameToLayer("Items"));

}

void RayCasting2()
{
Debug.DrawLine (sightStart2.position, sightEnd2.position, Color.black);
spotted = Physics2D.Linecast (sightStart2.position, sightEnd2.position, 1 << LayerMask.NameToLayer("Items"));

}

void Behaviours()
{
if (spotted == true) {
transform.Translate (direction * speed * Time.deltaTime);
speed = 2f;
} else if (spotted == false) {
speed = 0;
}
}

void OnTriggerExit2D (Collider2D col) {
if (col.tag == "object1") {
speed = 0;
CancelInvoke();
}
if (col.tag == "object2") {
speed = 0;
CancelInvoke();
}
if (col.tag == "object3") {
speed = 0;
CancelInvoke();
}
if (col.tag == "object4") {
speed = 0;
CancelInvoke();
}
}
}









share|improve this question



























    0















    I have a script that will make enemies look around an area for random objects within a scene, if the enemy spots the object then the enemy will move forward. However, this is not what I want the enemy to do, instead of the enemy moving forward, I want the enemy to move towards the object and then once the enemy reaches the object, I want the enemy to stop it's movement. I have different types of objects with different tags attached to it so I don't think moving the object using the object's tag name will be effective. I hope to find a way to move the enemies to the nearest object using the object's Layer name as all of my objects have the same layer name, meaning whatever object is spawn in to the scene the enemy will be able to move towards it. Is there a way to move my enemy towards an object when they have the object in sight? Thank you for your help!



    This is my code so far:



    public Transform sightStart, sightEnd, sightStart2, sightEnd2;

    public Vector3 direction = Vector3.right;
    public Vector3 direction2 = Vector3.right;

    public float speed = 2f;

    public bool spotted = false;
    public bool rotate, moveEnemy = false;

    public Camera mainCam;

    public GameObject EndSight, EndSight2;

    void Start () {
    speed = 2f;
    spotted = false;
    rotate = false;
    moveEnemy = false;
    mainCam = GameObject.Find ("Main Camera").GetComponent<Camera> ();

    }


    void Update () {
    Behaviours ();
    if (mainCam.WorldToScreenPoint (this.transform.position).x > Screen.width / 2) {
    direction.x = -1;
    InvokeRepeating ("EnemySight", 0, 10f);
    if (moveEnemy == false) {
    RayCasting ();
    Destroy (gameObject, 7f);
    }
    } else {
    direction.x = 1;
    InvokeRepeating ("EnemySight", 0, 10f);
    if (moveEnemy == false) {
    RayCasting2 ();
    Destroy (gameObject, 7f);
    }
    }
    }

    void EnemySight() {
    if (rotate == false) {
    if (mainCam.WorldToScreenPoint (this.transform.position).x > Screen.width / 2) {
    EndSight.transform.Translate (direction2 * speed * Time.deltaTime);
    direction2.x = 0;
    direction2.y = 1;
    StartCoroutine (wait1 ());
    } else {
    EndSight2.transform.Translate (direction2 * speed * Time.deltaTime);
    direction2.x = 0;
    direction2.y = 1;
    StartCoroutine (wait1 ());

    }
    } else if (rotate == true) {
    if (mainCam.WorldToScreenPoint (this.transform.position).x > Screen.width / 2) {
    EndSight.transform.Translate (direction2 * speed * Time.deltaTime);
    direction2.x = 0;
    direction2.y = -1;
    StartCoroutine (wait2 ());
    } else {
    EndSight2.transform.Translate (direction2 * speed * Time.deltaTime);
    direction2.x = 0;
    direction2.y = -1;
    StartCoroutine (wait2 ());
    }
    }
    }

    IEnumerator wait1() {
    yield return new WaitForSeconds (0.7f);
    rotate = true;
    }

    IEnumerator wait2() {
    yield return new WaitForSeconds (0.7f);
    rotate = false;
    }

    void RayCasting()
    {
    Debug.DrawLine (sightStart.position, sightEnd.position, Color.black);
    spotted = Physics2D.Linecast (sightStart.position, sightEnd.position, 1 << LayerMask.NameToLayer("Items"));

    }

    void RayCasting2()
    {
    Debug.DrawLine (sightStart2.position, sightEnd2.position, Color.black);
    spotted = Physics2D.Linecast (sightStart2.position, sightEnd2.position, 1 << LayerMask.NameToLayer("Items"));

    }

    void Behaviours()
    {
    if (spotted == true) {
    transform.Translate (direction * speed * Time.deltaTime);
    speed = 2f;
    } else if (spotted == false) {
    speed = 0;
    }
    }

    void OnTriggerExit2D (Collider2D col) {
    if (col.tag == "object1") {
    speed = 0;
    CancelInvoke();
    }
    if (col.tag == "object2") {
    speed = 0;
    CancelInvoke();
    }
    if (col.tag == "object3") {
    speed = 0;
    CancelInvoke();
    }
    if (col.tag == "object4") {
    speed = 0;
    CancelInvoke();
    }
    }
    }









    share|improve this question

























      0












      0








      0








      I have a script that will make enemies look around an area for random objects within a scene, if the enemy spots the object then the enemy will move forward. However, this is not what I want the enemy to do, instead of the enemy moving forward, I want the enemy to move towards the object and then once the enemy reaches the object, I want the enemy to stop it's movement. I have different types of objects with different tags attached to it so I don't think moving the object using the object's tag name will be effective. I hope to find a way to move the enemies to the nearest object using the object's Layer name as all of my objects have the same layer name, meaning whatever object is spawn in to the scene the enemy will be able to move towards it. Is there a way to move my enemy towards an object when they have the object in sight? Thank you for your help!



      This is my code so far:



      public Transform sightStart, sightEnd, sightStart2, sightEnd2;

      public Vector3 direction = Vector3.right;
      public Vector3 direction2 = Vector3.right;

      public float speed = 2f;

      public bool spotted = false;
      public bool rotate, moveEnemy = false;

      public Camera mainCam;

      public GameObject EndSight, EndSight2;

      void Start () {
      speed = 2f;
      spotted = false;
      rotate = false;
      moveEnemy = false;
      mainCam = GameObject.Find ("Main Camera").GetComponent<Camera> ();

      }


      void Update () {
      Behaviours ();
      if (mainCam.WorldToScreenPoint (this.transform.position).x > Screen.width / 2) {
      direction.x = -1;
      InvokeRepeating ("EnemySight", 0, 10f);
      if (moveEnemy == false) {
      RayCasting ();
      Destroy (gameObject, 7f);
      }
      } else {
      direction.x = 1;
      InvokeRepeating ("EnemySight", 0, 10f);
      if (moveEnemy == false) {
      RayCasting2 ();
      Destroy (gameObject, 7f);
      }
      }
      }

      void EnemySight() {
      if (rotate == false) {
      if (mainCam.WorldToScreenPoint (this.transform.position).x > Screen.width / 2) {
      EndSight.transform.Translate (direction2 * speed * Time.deltaTime);
      direction2.x = 0;
      direction2.y = 1;
      StartCoroutine (wait1 ());
      } else {
      EndSight2.transform.Translate (direction2 * speed * Time.deltaTime);
      direction2.x = 0;
      direction2.y = 1;
      StartCoroutine (wait1 ());

      }
      } else if (rotate == true) {
      if (mainCam.WorldToScreenPoint (this.transform.position).x > Screen.width / 2) {
      EndSight.transform.Translate (direction2 * speed * Time.deltaTime);
      direction2.x = 0;
      direction2.y = -1;
      StartCoroutine (wait2 ());
      } else {
      EndSight2.transform.Translate (direction2 * speed * Time.deltaTime);
      direction2.x = 0;
      direction2.y = -1;
      StartCoroutine (wait2 ());
      }
      }
      }

      IEnumerator wait1() {
      yield return new WaitForSeconds (0.7f);
      rotate = true;
      }

      IEnumerator wait2() {
      yield return new WaitForSeconds (0.7f);
      rotate = false;
      }

      void RayCasting()
      {
      Debug.DrawLine (sightStart.position, sightEnd.position, Color.black);
      spotted = Physics2D.Linecast (sightStart.position, sightEnd.position, 1 << LayerMask.NameToLayer("Items"));

      }

      void RayCasting2()
      {
      Debug.DrawLine (sightStart2.position, sightEnd2.position, Color.black);
      spotted = Physics2D.Linecast (sightStart2.position, sightEnd2.position, 1 << LayerMask.NameToLayer("Items"));

      }

      void Behaviours()
      {
      if (spotted == true) {
      transform.Translate (direction * speed * Time.deltaTime);
      speed = 2f;
      } else if (spotted == false) {
      speed = 0;
      }
      }

      void OnTriggerExit2D (Collider2D col) {
      if (col.tag == "object1") {
      speed = 0;
      CancelInvoke();
      }
      if (col.tag == "object2") {
      speed = 0;
      CancelInvoke();
      }
      if (col.tag == "object3") {
      speed = 0;
      CancelInvoke();
      }
      if (col.tag == "object4") {
      speed = 0;
      CancelInvoke();
      }
      }
      }









      share|improve this question














      I have a script that will make enemies look around an area for random objects within a scene, if the enemy spots the object then the enemy will move forward. However, this is not what I want the enemy to do, instead of the enemy moving forward, I want the enemy to move towards the object and then once the enemy reaches the object, I want the enemy to stop it's movement. I have different types of objects with different tags attached to it so I don't think moving the object using the object's tag name will be effective. I hope to find a way to move the enemies to the nearest object using the object's Layer name as all of my objects have the same layer name, meaning whatever object is spawn in to the scene the enemy will be able to move towards it. Is there a way to move my enemy towards an object when they have the object in sight? Thank you for your help!



      This is my code so far:



      public Transform sightStart, sightEnd, sightStart2, sightEnd2;

      public Vector3 direction = Vector3.right;
      public Vector3 direction2 = Vector3.right;

      public float speed = 2f;

      public bool spotted = false;
      public bool rotate, moveEnemy = false;

      public Camera mainCam;

      public GameObject EndSight, EndSight2;

      void Start () {
      speed = 2f;
      spotted = false;
      rotate = false;
      moveEnemy = false;
      mainCam = GameObject.Find ("Main Camera").GetComponent<Camera> ();

      }


      void Update () {
      Behaviours ();
      if (mainCam.WorldToScreenPoint (this.transform.position).x > Screen.width / 2) {
      direction.x = -1;
      InvokeRepeating ("EnemySight", 0, 10f);
      if (moveEnemy == false) {
      RayCasting ();
      Destroy (gameObject, 7f);
      }
      } else {
      direction.x = 1;
      InvokeRepeating ("EnemySight", 0, 10f);
      if (moveEnemy == false) {
      RayCasting2 ();
      Destroy (gameObject, 7f);
      }
      }
      }

      void EnemySight() {
      if (rotate == false) {
      if (mainCam.WorldToScreenPoint (this.transform.position).x > Screen.width / 2) {
      EndSight.transform.Translate (direction2 * speed * Time.deltaTime);
      direction2.x = 0;
      direction2.y = 1;
      StartCoroutine (wait1 ());
      } else {
      EndSight2.transform.Translate (direction2 * speed * Time.deltaTime);
      direction2.x = 0;
      direction2.y = 1;
      StartCoroutine (wait1 ());

      }
      } else if (rotate == true) {
      if (mainCam.WorldToScreenPoint (this.transform.position).x > Screen.width / 2) {
      EndSight.transform.Translate (direction2 * speed * Time.deltaTime);
      direction2.x = 0;
      direction2.y = -1;
      StartCoroutine (wait2 ());
      } else {
      EndSight2.transform.Translate (direction2 * speed * Time.deltaTime);
      direction2.x = 0;
      direction2.y = -1;
      StartCoroutine (wait2 ());
      }
      }
      }

      IEnumerator wait1() {
      yield return new WaitForSeconds (0.7f);
      rotate = true;
      }

      IEnumerator wait2() {
      yield return new WaitForSeconds (0.7f);
      rotate = false;
      }

      void RayCasting()
      {
      Debug.DrawLine (sightStart.position, sightEnd.position, Color.black);
      spotted = Physics2D.Linecast (sightStart.position, sightEnd.position, 1 << LayerMask.NameToLayer("Items"));

      }

      void RayCasting2()
      {
      Debug.DrawLine (sightStart2.position, sightEnd2.position, Color.black);
      spotted = Physics2D.Linecast (sightStart2.position, sightEnd2.position, 1 << LayerMask.NameToLayer("Items"));

      }

      void Behaviours()
      {
      if (spotted == true) {
      transform.Translate (direction * speed * Time.deltaTime);
      speed = 2f;
      } else if (spotted == false) {
      speed = 0;
      }
      }

      void OnTriggerExit2D (Collider2D col) {
      if (col.tag == "object1") {
      speed = 0;
      CancelInvoke();
      }
      if (col.tag == "object2") {
      speed = 0;
      CancelInvoke();
      }
      if (col.tag == "object3") {
      speed = 0;
      CancelInvoke();
      }
      if (col.tag == "object4") {
      speed = 0;
      CancelInvoke();
      }
      }
      }






      c# unity3d






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Jan 19 at 18:30









      wasicool2wasicool2

      799




      799
























          1 Answer
          1






          active

          oldest

          votes


















          0














          https://docs.unity3d.com/ScriptReference/Vector2.MoveTowards.html



          enemy.transform = Vector2.MoveTowards(enemy.transform, target.transform, speed * Time.deltaTime);



          If you want to stop the enemy a bit farther than the transform of the target, your target could be the hitPoint of the Raycast.



          Hope it helps.






          share|improve this answer
























          • Thank you for replying, I was just wondering how would I implement the vector target due to the fact that I have different types of objects that is instantiated into the game with different names and different tag names? Thank you again for your contribution. :)

            – wasicool2
            Jan 20 at 16:12











          • I am not sure if I understood your issue. But you could ask if the object is the type your are looking for, let me explain. You could do a base class (SearchableObject), if the object seen by the enemy is a searchableObject, then move towards it.

            – Jorge Fernandez Herrero
            Jan 20 at 18:36













          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54270141%2funity2d-move-enemy-towards-object-when-spotted%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          0














          https://docs.unity3d.com/ScriptReference/Vector2.MoveTowards.html



          enemy.transform = Vector2.MoveTowards(enemy.transform, target.transform, speed * Time.deltaTime);



          If you want to stop the enemy a bit farther than the transform of the target, your target could be the hitPoint of the Raycast.



          Hope it helps.






          share|improve this answer
























          • Thank you for replying, I was just wondering how would I implement the vector target due to the fact that I have different types of objects that is instantiated into the game with different names and different tag names? Thank you again for your contribution. :)

            – wasicool2
            Jan 20 at 16:12











          • I am not sure if I understood your issue. But you could ask if the object is the type your are looking for, let me explain. You could do a base class (SearchableObject), if the object seen by the enemy is a searchableObject, then move towards it.

            – Jorge Fernandez Herrero
            Jan 20 at 18:36


















          0














          https://docs.unity3d.com/ScriptReference/Vector2.MoveTowards.html



          enemy.transform = Vector2.MoveTowards(enemy.transform, target.transform, speed * Time.deltaTime);



          If you want to stop the enemy a bit farther than the transform of the target, your target could be the hitPoint of the Raycast.



          Hope it helps.






          share|improve this answer
























          • Thank you for replying, I was just wondering how would I implement the vector target due to the fact that I have different types of objects that is instantiated into the game with different names and different tag names? Thank you again for your contribution. :)

            – wasicool2
            Jan 20 at 16:12











          • I am not sure if I understood your issue. But you could ask if the object is the type your are looking for, let me explain. You could do a base class (SearchableObject), if the object seen by the enemy is a searchableObject, then move towards it.

            – Jorge Fernandez Herrero
            Jan 20 at 18:36
















          0












          0








          0







          https://docs.unity3d.com/ScriptReference/Vector2.MoveTowards.html



          enemy.transform = Vector2.MoveTowards(enemy.transform, target.transform, speed * Time.deltaTime);



          If you want to stop the enemy a bit farther than the transform of the target, your target could be the hitPoint of the Raycast.



          Hope it helps.






          share|improve this answer













          https://docs.unity3d.com/ScriptReference/Vector2.MoveTowards.html



          enemy.transform = Vector2.MoveTowards(enemy.transform, target.transform, speed * Time.deltaTime);



          If you want to stop the enemy a bit farther than the transform of the target, your target could be the hitPoint of the Raycast.



          Hope it helps.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Jan 19 at 18:58









          Jorge Fernandez HerreroJorge Fernandez Herrero

          11




          11













          • Thank you for replying, I was just wondering how would I implement the vector target due to the fact that I have different types of objects that is instantiated into the game with different names and different tag names? Thank you again for your contribution. :)

            – wasicool2
            Jan 20 at 16:12











          • I am not sure if I understood your issue. But you could ask if the object is the type your are looking for, let me explain. You could do a base class (SearchableObject), if the object seen by the enemy is a searchableObject, then move towards it.

            – Jorge Fernandez Herrero
            Jan 20 at 18:36





















          • Thank you for replying, I was just wondering how would I implement the vector target due to the fact that I have different types of objects that is instantiated into the game with different names and different tag names? Thank you again for your contribution. :)

            – wasicool2
            Jan 20 at 16:12











          • I am not sure if I understood your issue. But you could ask if the object is the type your are looking for, let me explain. You could do a base class (SearchableObject), if the object seen by the enemy is a searchableObject, then move towards it.

            – Jorge Fernandez Herrero
            Jan 20 at 18:36



















          Thank you for replying, I was just wondering how would I implement the vector target due to the fact that I have different types of objects that is instantiated into the game with different names and different tag names? Thank you again for your contribution. :)

          – wasicool2
          Jan 20 at 16:12





          Thank you for replying, I was just wondering how would I implement the vector target due to the fact that I have different types of objects that is instantiated into the game with different names and different tag names? Thank you again for your contribution. :)

          – wasicool2
          Jan 20 at 16:12













          I am not sure if I understood your issue. But you could ask if the object is the type your are looking for, let me explain. You could do a base class (SearchableObject), if the object seen by the enemy is a searchableObject, then move towards it.

          – Jorge Fernandez Herrero
          Jan 20 at 18:36







          I am not sure if I understood your issue. But you could ask if the object is the type your are looking for, let me explain. You could do a base class (SearchableObject), if the object seen by the enemy is a searchableObject, then move towards it.

          – Jorge Fernandez Herrero
          Jan 20 at 18:36




















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54270141%2funity2d-move-enemy-towards-object-when-spotted%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Liquibase includeAll doesn't find base path

          How to use setInterval in EJS file?

          Petrus Granier-Deferre