A have a problem with the random position of spawns in my spawner script. I didn’t find a good solution online but i haven’t looked long, so i thought of my own version:
I need to spawn enemies with Instantiate() on the plain. The position needs to be out of bounderies but not to far to save some cpu. So there is basicly an inner box in the middle that is not allowed and an outer box, between them thay should spawn. That was the goal.
Here is the code with notes:
void Start()
{
innerBorderX = GameObject.Find("BodenT").GetComponent<BackgroundScroller>().rightEdge; //16
innerBorderY = GameObject.Find("BodenT").GetComponent<BackgroundScroller>().topEdge; //20
outerBorderX = innerBorderX + 10;
outerBorderY = innerBorderY + 10;
}
void SpawnEnemy() //The random Selection of enemies needs to be implemented
{ //Instantiate water Elemental
GameObject a = Instantiate(waterElemental) as GameObject;
if (Random.Range(0, 1) == 1){ //rolling dice for priority 1 = horizontal 0 = vertical
randomX = Random.Range(-outerBorderX * 100, outerBorderX * 100) / 100; //setting an X value from full span
if(randomX < -innerBorderX|| randomX > innerBorderX) //when X is out of Bounderies, Y can have full span
{
randomY = Random.Range(-outerBorderY * 100, outerBorderY * 100) / 100; //setting an Y value from full span
}
else //when X is in the Bounderies, Y needs to be top or Bottom span
{
if (Random.Range(0, 1) == 1) //rolling dice for priority 1 = top, 0 = bottom
{
randomY = Random.Range(innerBorderY * 100, outerBorderY * 100) / 100; //setting Y value from top span
}
else
{
randomY = Random.Range(-outerBorderY * 100, -innerBorderY * 100) / 100; //setting Y value from bottom span
}
}
} //RandomX und RandomY werden ausgewertet
else
{ //if vertical has priority
randomY = Random.Range(-outerBorderY * 100, outerBorderY * 100) / 100; //setting Y value from full span
if(randomY < -innerBorderY|| randomY > innerBorderY) //wenn an Y is out of Bounderies, X can have full span
{
randomX = Random.Range(-outerBorderX * 100, outerBorderX * 100) / 100; //setting an X value from full span
}
else
{ //when Y is in the Bounderies, X needs to be left or right span
if (Random.Range(0, 1) == 1){ //rolling dice for priority 1 = left, 0 = right
randomX = Random.Range(-outerBorderX * 100, -innerBorderX * 100) / 100; //setting an X value from left span
}
else
{
randomX = Random.Range(innerBorderX * 100, outerBorderX * 100) / 100; //setting an X value from right span
}
}
}
a.transform.position = new Vector2(randomX, randomY); //setting the position of "a" to random out of Bounderies
}
what happens here is that the enemies spawn in a rectangle but the left edge doesn’t spawn anything… i can’t see why this happens, please help.