Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Question 2d enemy stops moving

Discussion in '2D' started by dtilgner, Jun 14, 2020.

  1. dtilgner

    dtilgner

    Joined:
    May 23, 2020
    Posts:
    4
    Hello guys,

    i don't know if this is the right section, first time asking any questions.
    My problem is the following:
    I have an enemy in my 2d platformer that is supposed to run in one direction until it reaches a cliff or a wall, then run back. This behaviour is working just fine. It turns a few times to run back and forth. But at some time it just stops running. Did someone experience something equivalent?

    In the Update() method of my script I call the following function:
    Code (CSharp):
    1.     private void Move() {
    2.         if (!facingRight)
    3.         {
    4.             rigidbody2D.velocity = new Vector2(-speed, rigidbody2D.velocity.y);
    5.         }
    6.         else if (facingRight)
    7.         {
    8.             rigidbody2D.velocity = new Vector2(speed, rigidbody2D.velocity.y);
    9.         }
    10.     }
    And I am switching facingRight every time the enemy would fall off or run into a wall.
    I don't really know what I am doing wrong..
     
  2. ToXicEboLa

    ToXicEboLa

    Joined:
    Jun 1, 2020
    Posts:
    6
    Try implementing the movement by changing transform.position in the FixedUpdate() function. At times the updating velocity in RigidBody component to move doesn't work if there are multiple colliders set as triggers or any other weird collisions. I have had experience with somewhat similar bug and after I changed my movement logic everything worked out fine. Comment this code out and implement movement using transform.position and see if it works.
     
    dtilgner likes this.
  3. dtilgner

    dtilgner

    Joined:
    May 23, 2020
    Posts:
    4
    Thanks for the fast reply =) It now works just as I wanted it!