- Home /
C# 2d Spawn Randomly along Camera Borders
I'm trying to make a script that spawns gameobjects randomly along the main camera's border. I was able to make the generate randomly but I'm not sure how to get the value's for the camera's borders. Are there stored variables like camera.border.x or something? I was able to find camera.orthographicSize but it doesn't have any vector3 coordinates.
using UnityEngine;
using System.Collections;
public class SpawnAroundCameraBorders: MonoBehaviour {
public GameObject someGameObject;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (Input.GetMouseButton(0)){
SpawnRandom();
}
}
public void SpawnRandom()
{
//Vector3 screenPosition = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width/2, Screen.height/2, Camera.main.nearClipPlane+5)); //will get the middle of the screen
Vector3 screenPosition = Camera.main.ScreenToWorldPoint(new Vector3(Random.Range(0,Screen.width), Random.Range(0,Screen.height), Camera.main.farClipPlane/2));
Instantiate(someGameObject,screenPosition,Quaternion.identity);
}
}
Comment
Answer by Jean-Fabre · Apr 04, 2016 at 08:51 AM
Hi,
Check Out the Lobby Networking Demo https://www.assetstore.unity3d.com/en/#!/content/41836
it spawns asteroids from the the screen sides. it plays with camera orthosize and ratio to properly setup the initial positions on the border of the screen.
Vector2 dir = Random.insideUnitCircle;
Vector3 position = Vector3.zero;
if(Mathf.Abs(dir.x) > Mathf.Abs(dir.y))
{//make it appear on the side
position = new Vector3( Mathf.Sign(dir.x)* Camera.main.orthographicSize * Camera.main.aspect,
0,
dir.y * Camera.main.orthographicSize);
}
else
{//make it appear on the top/bottom
position = new Vector3(dir.x * Camera.main.orthographicSize * Camera.main.aspect,
0,
Mathf.Sign(dir.y) * Camera.main.orthographicSize);
}
Bye,
Jean