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);
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);
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.