- Home /
Side scroller spawns at different Y
I am making a space shooter, I have waves of enemies coming in from the right but I don't want them spawning close on the Y axis one after another. I have tried comparing the new vector with the previous vector to see if it's less or more by 2 but it doesn't seem to be working. I'm new to unity and C# so if anyone could help that would be great!
void getSpawn()
{
counter = 0;
if (firstSpawn == true) { // First spawn has no previous
spawnPosition = new Vector3 (5, Random.Range (-spawnValues.y, spawnValues.y), spawnValues.z);
firstSpawn = false;
} else {
previousPosition = spawnPosition;// set previous
spawnPosition = new Vector3 (5, Random.Range (-spawnValues.y, spawnValues.y), spawnValues.z);
Debug.Log(spawnPosition.y);
Debug.Log(previousPosition.y);
while (previousPosition.y < spawnPosition.y -2 || previousPosition.y > spawnPosition.y +2) {
spawnPosition = new Vector3 (5, Random.Range (-spawnValues.y, spawnValues.y), spawnValues.z);
previousPosition = spawnPosition;
counter++;
Debug.Log ("hit while");
if (counter == 20){ //stops game from freezing whilst testing.
break;}
}
Thanks Calum
Comment
Answer by NecrosDk · Mar 08, 2017 at 03:46 PM
I would make a List and fill it on start() with like 20 different y positions within a given range:
List<float> possibleSpawns = new List<float>();
float distanceBetweenSpawnPoints
int previousRand = 0;
int rand = 0;
void Start(){
for (int i = 0; i < 20; i++){
possibleSpawns.Add(distanceBetweenSpawnPoints*i);
//Fills the list with some spawnPoints
}
}
void Update(){
while (rand == previousRand){
rand = Random.Range(0, possibleSpawns.Count); //Roll a random within the list
}
previousRand = rand;
spawnPosition = (xValue, possibleSpawns[rand], zValue);
}