Search code examples
c#unity-game-enginegame-development

How can I stop the movement of a gameObject upon collision with another gameObject (Unity)


I am trying to create a game, and in said game I want the enemy to stop moving towards the player after colliding with them so that the player has enough time to get knocked back before being hit again.

void Update()
    {
        float distFromPlayer = Mathf.Abs(player.transform.position.x - transform.position.x);

        if (!isKnockback && !isAttacking)
        {
            float Direction = Mathf.Sign(player.transform.position.x; - transform.position.x);
            Vector2 MovePos = new Vector2(
                transform.position.x + Direction * speed * Time.deltaTime, //MoveTowards on 1 axis
                transform.position.y
            );
            transform.position = MovePos;
        }
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.gameObject.tag == "Player")
        {
            Attack();
        }
    }

    IEnumerator Attack()
    {
        isAttacking = true;
        yield return new WaitForSeconds(1);
        isAttacking = false;
    }

I have tried: setting the RigidBody's velocity to 0, setting the enemy's speed to 0, doing a Vector2.MoveTowards with the target position as the enemy's current position. All of these resulted in a no change from just having the enemy intentionally keep moving towards the player.

I would like to reiterate that I don't want the enemy to completely freeze, but just stop moving towards the player.


Solution

  • I believe there is a small issue with your code that made it not work properly.

    The proper way of invoking an IEnumerator is with StartCoroutine(Attack());

    Basically invoking an IEnumerator like a regular method doesn't do anything, and made your Enemy move even though is triggered by the Player.

    Learn more about how to use StartCoroutine on Unity's official documentation: https://docs.unity3d.com/ScriptReference/MonoBehaviour.StartCoroutine.html

    Hope this fixed your issue!