Pause movement on collision

Hello again!

I have made a script which should stop the movement of an enemy when it touches the player. When the enemy stops moving it charges an attack and on the 3rd second he attacks. (If the player is still within the enemy collider he takes damage). After the attack which should take 3 seconds, he continues moving towards the player.

I have made a script which makes the enemy move torwards the player and stop his movement when he the collider is triggered. My problem is that he does not continue walking towards the player (after the 3 seconds). Could you perhaps help me to modify my script so that the enemy after the 3s pause continues moving towards the player?

The code:
using UnityEngine;
using System.Collections;

public class ZombieMovement : MonoBehaviour {

	public Transform player;
	public float moveSpeed;
	public float AttackAnimDuration = 3f;
	private bool paused;

	IEnumerator delay()
	{
		paused = true;
		yield return new WaitForSeconds(AttackAnimDuration);
		paused = false;
	}
		
		void Update () {

		if (paused)
		{
			return;
		}
	
		float move = moveSpeed * Time.deltaTime;
		transform.position = Vector3.MoveTowards (transform.position, player.position, move);

	}
	void OnTriggerEnter2D(Collider2D col)
	{
		 
		if (col.gameObject.tag == "Player") 

		{
			paused = true;
		
		}
	
	
	}
	
}

Thanks in advance :slight_smile:

/Taegos

You’re not calling the delay() coroutine and because of that after the collision your paused variable remains false.

void OnTriggerEnter2D(Collider2D col)
{
    if (col.gameObject.tag == "Player")
    {
        StartCoroutine(delay());
    }
}

This should work as you described.

paused = true;
yield return new WaitForSeconds(AttackAnimDuration); // you return here, so you never change paused to false.
paused = false;

Your problem is that pause never gets set to false.

I would do it like this:

using UnityEngine; using System.Collections;
public class ZombieMovement : MonoBehaviour {
    public Transform player;
    public float moveSpeed;
    public float AttackAnimDuration = 3f;
    private bool paused = false;
 
    private attackTimer = 0;
         
        void Update () {
 
            if (!paused){
                float move = moveSpeed * Time.deltaTime;
                transform.position = Vector3.MoveTowards (transform.position, player.position, move);
            } else {
                attackTimer += Time.deltaTime;
                if (attackTimer >= AttackAnimDuration) {
                    attackTimer = 0;
                    paused = false;
                }
            }
        }
    void OnTriggerEnter2D(Collider2D col)
    {
          
        if (col.gameObject.tag == "Player") 
 
        {
            paused = true;
         
        }
    }
}

(untested - let me know if there are any problems)