- Home /
random place generator
public class enemySpawner : MonoBehaviour
{ public GameObject enemyPrefab;
public float spawnTime;
Vector2 screenBounds;
void Start()
{
screenBounds = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, Camera.main.transform.position.z));
StartCoroutine(alienWave());
}
void enemySpawn()
{
GameObject a = Instantiate(enemyPrefab) as GameObject;
a.transform.position = new Vector2(screenBounds.y * 2, Random.Range(-screenBounds.x, screenBounds.x));
}
IEnumerator alienWave()
{
while (true)
{
yield return new WaitForSeconds(spawnTime);
enemySpawn();
}
}
}
I keep spawning aliens only on this side. any solutions?
the problem is there
a.transform.position = new Vector2(screenBounds.y * 2, Random.Range(-screenBounds.x, screenBounds.x));
if you see on your global space, problably x axis is the horizontal axis , try some like
a.transform.position = new Vector2((Random.Range (0,1))*screenBounds.y * 2, Random.Range(-screenBounds.x, screenBounds.x));
(Random.Range (0,1)
returns a int
either 0 or 1, not a float value betweem them so, the aliens will spawn on the left y = 0
or right y = screenBounds.y*2
Answer by Dimitris4 · Apr 26, 2019 at 12:03 PM
@DCordoba its not the same except instead of spawning on the sides it spawns in the middle. Any other idea?
I forgot to Random.Range($$anonymous$$, max) is with $$anonymous$$ inclusive but max exclusive so, x axis always will be 0...
ammm, sorry, my bad xd
try, a.transform.position = new Vector2((Random.Range (0,2))*screenBounds.y * 2, Random.Range(-screenBounds.x, screenBounds.x));
this will do random between 0 and 1
also please provide info about camera location, I believed, purely empiric to (0,0) was on the left-bottom part of the scene... this doesnt seem to be the case, so...
lets make it jump between two fixed values, (-1 and 1) if your camera is centered on 0 this... should work
int randYFromN1To1 = 2*(Random.Range (0,2)) - 1; //this jump between -1 and 1 without touch intermediate values
transform.position = new Vector2 ((randYFromN1To1)*screenBounds.y * 2, Random.Range (-screenBounds.x, screenBounds.x));