How to spawn objects from the right side outside of view range?
I'm still very green but i'm learning. After many videos and searches i'm close but not quite there yet with what i'm trying to achieve.
My game scrolls from left to right automatically and i'm trying to get my enemy spawner script to properly generate enemies off the right side of the screen. a few tutorials had me find the ranges i needed. mine are -4 and 4.1 on the Y. i tried using a tutorial where the spawn was from the top of the screen down to the character and i swapped the X for Y in my script.
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class EnemySpawner2 : MonoBehaviour {
public GameObject enemyrocket;
float randY;
Vector2 whereToSpawn;
public float spawnRate = 5f;
float nextSpawn = 0;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (Time.time > nextSpawn) {
nextSpawn = Time.time + spawnRate;
randY = Random.Range (4.1f, 4.0f);
whereToSpawn = new Vector2 (randY, transform.position.x);
Instantiate (enemyrocket, whereToSpawn, Quaternion.identity);
}
}
}
tested it and my enemies spawned right on or around my character. then i tried learning from a space shooter tutorial where the instructor used viewport to world point. i got spawns but they were above the top of my game view area instead of off to the right side.
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class EnemySpawner : MonoBehaviour {
public GameObject enemyrocket;
float maxSpawnRateInSeconds = 5f;
// Use this for initialization
void Start ()
{
Invoke ("SpawnEnemy", maxSpawnRateInSeconds);
}
// Update is called once per frame
void Update ()
{
} void SpawnEnemy () { Vector2 min = Camera.main.ViewportToWorldPoint (new Vector2 (0, 0)); Vector2 max = Camera.main.ViewportToWorldPoint (new Vector2 (1, 1)); GameObject anEmemy = (GameObject)Instantiate (enemyrocket); anEmemy.transform.position = new Vector2 (Random.Range (min.y, max.y), max.x); } } any help is always appreciated. thanks in advance.