- Home /
Spawning Enemies off the screen w/ scrolling background
I am working on a 2D sidescroller, the player is on the left and I want to asteroids to spawn off screen on the right. I have script for a scrolling background and a script for random spawning, but I cannot figure out a way to make it so that the asteroids continuously spawn off screen. using UnityEngine; using System.Collections;
Spawning Script
public class GameController : MonoBehaviour {
public GameObject hazard;
public Vector3 spawnValues;
public int hazardCount;
public float spawnWait;
public float startWait;
public float waveWait;
void Start ()
{
StartCoroutine (SpawnWaves ());
}
IEnumerator SpawnWaves ()
{
yield return new WaitForSeconds (startWait);
while (true)
{
for (int i = 0; i < hazardCount; i++)
{
Vector3 spawnPosition = new Vector3 (Random.Range (-spawnValues.x, spawnValues.x), spawnValues.y, spawnValues.z);
Quaternion spawnRotation = Quaternion.identity;
Instantiate (hazard, spawnPosition, spawnRotation);
yield return new WaitForSeconds (spawnWait);
}
yield return new WaitForSeconds (waveWait);
}
}
}
Have you tried setting the SpawnValues.x to somewhere higher than Screen.size? I'm not sure if it works tho, I haven't tried.
Answer by robertbu · Apr 24, 2014 at 06:47 AM
An easy way to make this happen is to use Viewport coordinates. Viewport coordinates go from 0.0 in the lower left, to 1.0 in the upper right. So you can use a 'x' value of line 1.1 for off screen creation. So you would do something like this:
Vector3 pos = Vector3(1.1, Random.value, someValue);
pos = Camera.main.ViewportToWorldPoint(pos);
'someValue' is the distance in front of the camera to spawn the object. Note I'm a bit confused by your code now since it spawns at random on the 'x' axis but has a fixed 'y' and 'z' position for spawning.
Your answer
Follow this Question
Related Questions
GuiText instantiation at position? 0 Answers
How to make camera position relative to a specific target. 1 Answer
How to change main camera and access to the other scripts?? 0 Answers
Android Unity ARCore camera access 0 Answers
OnRenderImage in one of the two cameras, Android showing only post processed camera. 1 Answer