Once every 2 seconds, move the object to random coordinates

I want my enemy to move to a random X position between -2.4 and 2.4 every 2 seconds, but he moves in jerks and for a very small distance. I suspect that the problem is in speed * Time.deltaTime, but I don’t know how to fix it

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Random=UnityEngine.Random;

public class EnemyController : MonoBehaviour
{
    public Transform enemy;
    private float random;
    [SerializeField] private float speed = 10f;

    void Start()
    {
        StartCoroutine(MoveEnemy());
    }

    IEnumerator MoveEnemy()
    {
        while (!MainGame.lose)
        {
            yield return new WaitForSeconds(2);

            random = Random.Range(-2.4f, 2.4f);
            Debug.Log(random);
            enemy.transform.position = Vector2.MoveTowards(enemy.position,
                new Vector3(random, enemy.position.y),
                speed * Time.deltaTime);
        }
    }
}

>Solution :

You are moving the enemy only once every two seconds. To me it sounds like you rather want to constantly move the enemy but only choose a new target position every 2 seconds so e.g.

// you can directly make Start a Coroutine by changing its return type 
IEnumerator Start()
{
    while (!MainGame.lose)
    {
        var random = Random.Range(-2.4f, 2.4f);
        var targetPosition = new Vector3(random, enemy.position.y);

        for(var time = 0f; time < 2f; time += Time.deltaTime)
        {
            // need to check within here since otherwise it would always try to finish the for loop
            if(MainGame.lose) 
            {
                // quits from this entire routine
                yield break;
            }

            enemy.position = Vector2.MoveTowards(enemy.position, targetPosition, speed * Time.deltaTime);

            // this basically means continue in the next frame
            yield return null;

            if(enemy.position == targetPosition) 
            {
                // quits the for loop and basically starts again from var random = ...
                break;
            }
        }
    }
}

So for up to two seconds you try to reach this random target with a constant linear movement and you select a new random target position if you either exceed 2 seconds or reached the target before that

Leave a Reply