Hi everybody.
I have been working on something to make the enemies on my game move on random directions every certain ammount of seconds. The problem here is that Random.Range I made for the directions runs every single frame so the enemies change direction every frame and the movement looks bad.
Also, if I use something like Random.Range(-5f, 5f); Is it going to choose one of those two or will it choose one of the 10 numbers that are between -5 and 5?
Here is my code for you to take a look at it
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MoveEnemies : MonoBehaviour
{
public float speed = 40.0f;
public float xRange = 7;
public float upBoundary = 4;
public float downBoundary = -2;
private float startDelay = 0.5f;
private float startInterval = 5.0f;
// Start is called before the first frame update
void Start()
{
InvokeRepeating("EnemieMovement", startDelay, startInterval);
}
// Update is called once per frame
void Update()
{
if (transform.position.x < -xRange)
{
transform.position = new Vector3(-xRange, transform.position.y, transform.position.z);
}
if (transform.position.x > xRange)
{
transform.position = new Vector3(xRange, transform.position.y, transform.position.z);
}
// Screen limits for y
if (transform.position.y < downBoundary)
{
transform.position = new Vector3(transform.position.x, downBoundary, transform.position.z);
}
if (transform.position.y > upBoundary)
{
transform.position = new Vector3(transform.position.x, upBoundary, transform.position.z);
}
}
IEnumerator GoRandom()
{
// This will wait 1 second like Invoke could do, remove this if you don't need it
yield return new WaitForSeconds(1);
float timePassed = 0;
while (timePassed < 3)
{
transform.Translate(Vector3.right * Time.deltaTime * Random.Range(-speed, speed));
transform.Translate(Vector3.forward * Time.deltaTime * Random.Range(-speed, speed));
timePassed += Time.deltaTime;
yield return null;
}
}
void EnemieMovement()
{
StartCoroutine(GoRandom());
}
}
[ICODE]
[/ICODE]