I have a problem with a game I an making. Using Random.Rang I am spawning enemies along the y axis (in different positions of course) One issue that I have is that while spawning the cars are “clumping”. For example 3 or 4 cars might be spawned quite close to each other making the game boring. Since Random.Range is not biased is their a away of preventing this clumping.
Suggestion:
Maybe is it possible to detect where the most recent car has been spawned and avoid spawning the car near that position. Thanks.
A picture of the problem is attached.
Here is my code in case you want it (Mean is the enemy in case you were confused):
using UnityEngine;
using System.Collections;
public class Enemy : MonoBehaviour {
public GameObject Mean;
public float MeanSpeed = 5f;
public float delayTimer = 1f;
private float timer;
private float Maxy;
private float Miny;
void Start () {
timer = delayTimer;
Maxy = 2.2f;
Miny = -2.2f;
}
void Update () {
timer -= Time.deltaTime;
if (timer <= 0) {
Vector3 enemyPos = new Vector3 (10, Random.Range (Miny, Maxy),0);
GameObject Enemy = Instantiate (Mean, enemyPos, Quaternion.identity) as GameObject;
Enemy.rigidbody2D.velocity = new Vector3 (-MeanSpeed, 0);
timer = delayTimer;
}
}
}
You could store the previous spawn y position and then check the Mathf.Abs(differenceBetweenPreviousPositionAndNextRandomRange) if it’s big enough before spawning, and spawn if it’s big enough, or keep calling and checking Random.Range again if they’re too close together until you get a desirable number.
Be careful that your minimum distance isn’t too big though, or you might go into an infinite loop where it can’t generate a number big enough while still being within the range of Miny and Maxy.
What’s with your field names, by the way? Why do some of them start with big letters and some are camelCase and some are PascalCase?