- Home /
Spawning Enemies randomly within the screen
Hi I have a script that spawn enemies in a certain range(defined for a particular screen size),I want to spawn the enemies within the screen irrespective of there size.
public class SpawnEnemy : MonoBehaviour {
public GameObject[] Enemy;
int EnemyNo;
public float maxPos = 6f;
public float delayTimer = 0.5f;
float timer;
void Start()
{
timer = delayTimer;
}
void Update()
{
timer -= Time.deltaTime;
if (timer <= 0)
{
Vector3 carPos = new Vector3(Random.Range(-6f,6f), transform.position.y, transform.position.z);
EnemyNo = Random.Range(0, 11);
Instantiate(Enemy[EnemyNo], carPos, transform.rotation);
timer = delayTimer;
}
}
}
I want Range should be according to screen size,I have tried to use clamp enemies within the screen and make the range higher to cover all screen size but it make spawning enemies on the corner more than in center.
Thanks in Advance
Answer by madks13 · Jul 10, 2018 at 08:45 AM
Umm, use the screen size to get a random number n between 0 and (width * height), then get coords
y = n / width
x = n - (y * width)
then spawn at screen point (x, y)
How to get screen size and its height and width? By using screen.height and screen.width it gives the no of pixels and i want coordinates. can you make these changes to my code ?
Use Camera.main.ScreenToWorldPoint(...) to convert screen pixel coordinates to world coordinates