Randomly Spawn Outside The Camera Field of View
I've been at this for a while now and can't seem to find a solution to my problem. I am trying to get the enemy to randomly spawn outside of the camera field of view. The problem I am having is that when ever I play the game, the enemy's always spawn in the corner of the screen. (I'm just using blocks because of testing)
Here is my scripts:
public GameObject[] enemy;
public int amount;
private Vector3 spawnPoint;
private float camMin;
private float camMax;
void Start()
{
camMin = Camera.main.orthographicSize;
camMax = Camera.main.orthographicSize + 2;
}
void Update ()
{
enemy = GameObject.FindGameObjectsWithTag ("Enemy");
amount = enemy.Length;
if (amount != 10)
{
InvokeRepeating ("spawnEnemy", 1f, 2f);
}
}
void spawnEnemy()
{
spawnPoint.x = Random.Range (camMin,camMax);
spawnPoint.y = Random.Range (camMin,camMax);
spawnPoint.z = 0;
Instantiate (enemy [UnityEngine.Random.Range (0, enemy.Length - 1)],spawnPoint, Quaternion.identity);
CancelInvoke ();
}
Thanks for the help!
Answer by GerPronouncedGrr · Jun 25, 2016 at 03:11 PM
Camera.OrthographicSize
returns half the vertical size of the orthographic viewing volume. So, essentially, any point in the outer 50% of the viewable area, or less (horizontally) if you're in widescreen. Try adding to this value (for both camMin
and camMax
), or perhaps switch to using pixelHeight
and pixelWidth
and see if you get better results.
Your answer
Follow this Question
Related Questions
How to spawn objects from the right side outside of view range? 0 Answers
Why doesn't random range work? 1 Answer
C# Instantiate multiple objects at unique positions within a set range 1 Answer
objects of same parrent random scale/size(xy and z) 0 Answers
random question without repetition 0 Answers