Check if player changed position and add delay

Hello i have this code in Update, it makes Enemy follow player.
How do i add delay before doing this code with timer.
Also how do i make this delay every time player changes his position.

transform.position = Vector2.MoveTowards(this.transform.position, player.transform.position, speed * Time.deltaTime);

2 Answers

2

you can use invoke in update and put delay there

  Invoke ("moveEnemy", 2);

and make a funtion with enemy move line

transform.position = Vector2.MoveTowards(this.transform.position, (destination * progress) + start * (1 - progress), speed * Time.deltaTime);

Yea, but how do i delay it each time player changes his transform.

–

just call the invoke in update it called each time moveEnemy after 2sec

–

Thanks it works now!

–

welcome !!!!!!!!

–

Whenever you say “wait” and “Unity” in the same sentence you should make a coroutine. In this case the code would look something like this:

private IEnumerator LookForPlayer(float t) //t - time in seconds to wait before looking
{ 
    yield return new WaitForSeconds(t);
    transform.position = Vector2.MoveTowards(this.transform.position, (destination * progress) + start * (1 - progress), speed * Time.deltaTime);
}

if you also want to look for player only when it changes it’s position, you probably would need to store his location in some variable, and constantly check if current position differs from your stored value, like this:

private float delay = 2f
private Vector3 old_player_position;
GameObject player;

private void Update(){
    if(old_player_position != player.transform.position)
    {
        StartCoroutine(LookForPlayer(delay));
        old_player_position = player.transform.position;
    }
}

private IEnumerator LookForPlayer(float t) //t - time in seconds to wait before looking
{ 
    yield return new WaitForSeconds(t);
    transform.position = Vector2.MoveTowards(this.transform.position, (destination * progress) + start * (1 - progress), speed * Time.deltaTime);
}

I can’t compile code in my brain, so it is not perfect, but I think you got the idea.

but if player is not moving how it gonna move enemy ? ig there is no need to check that

–

How do i set destination, progress and start variables?

–

Ok, I see the problem now

–