I am trying to change this script that I found online https://pressstart.vip/tutorials/2018/09/25/58/spawning-obstacles.html to work with a orthographic camera because that is what my game uses. At the moment it only works with perspective cameras and I don't really know how this works cause I have not really touched the camera matrix. Here is the code for the script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class deployAsteroids : MonoBehaviour {
public GameObject asteroidPrefab;
public float respawnTime = 1.0f;
private Vector2 screenBounds;
// Use this for initialization
void Start () {
screenBounds = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, Camera.main.transform.position.z));
StartCoroutine(asteroidWave());
}
private void spawnEnemy(){
GameObject a = Instantiate(asteroidPrefab) as GameObject;
a.transform.position = new Vector2(screenBounds.x * -2, Random.Range(-screenBounds.y, screenBounds.y));
}
IEnumerator asteroidWave(){
while(true){
yield return new WaitForSeconds(respawnTime);
spawnEnemy();
}
}
}
My goal is to change the script to make it work correctly with a orthographic camera. (The indentation is messed up and that is not the problem).
CodePudding user response:
For some reason the code is using Camera.main.transform.position.z
for the camera depth component. This value will be negative in a typical camera setup in a 2d game.
So it's finding the left side of the screen by following the right edge of the frustum behind the camera. Very odd. You can't follow the right side of the frustum to find where the left side of the screen if it's orthographic so it is no surprise that it doesn't work.
Instead, just use the left side of the frustum and make the depth positive by negating that component:
screenBounds = Camera.main.ViewportToWorldPoint(
new Vector3(0f, 0f, -Camera.main.transform.position.z));