0

I dont know how to fix the time it takes to move from the current position to the target position(wp). It doesnt feel clean and is annoyingly fast if the distance is too small.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Enemy : MonoBehaviour
{
    //move
    public GameObject player;
    public float speed = 20;
    float WPradius = 1;
    private Vector2 wp;

    void Update()
    {
        if (Vector2.Distance(wp, transform.position) < WPradius)
        {
            wp = new Vector2(player.transform.position.x, UnityEngine.Random.Range(3f, -3f));
            
            //do stuff
        }

        transform.position = Vector2.MoveTowards(transform.position, wp, Time.deltaTime * speed);
    }
}
  • So the time between some point and time and the `Enemy` reaching its destination should be fixed. What exactly is the first moment in time? The moment the `Enemy` is created? The moment some other method is called? Objective is unclear. – Ruzihm Nov 16 '21 at 19:28
  • In general this is way easier to control using Coroutines – derHugo Nov 16 '21 at 19:56
  • @Ruzihm the time the `Enemy` is created is 0 and the time it has reached `wp` is x. At this point `wp` is redifined and the circle repeats. I want to fix the time so the time between 0 and x is the same regardless of the distance between the current position and `wp`. – Mr. yeet Nov 17 '21 at 07:57
  • @Mr.yeet use [`Vector2.Lerp`](https://docs.unity3d.com/ScriptReference/Vector2.Lerp.html) and as a factor use a field `timer` you increase from `0` to `1` within the desired time e.g. by doing `factor += Time.deltaTime / durationInSeconds;` if you do this directly in `Update` or via a Coroutine is up to you but in my opinion as said it is just way easier to control and maintain using [Coroutines](https://docs.unity3d.com/Manual/Coroutines.html) – derHugo Nov 17 '21 at 12:01

0 Answers0