将透视脚本更改为正交统一 2d

Change perspective script to orthographic unity 2d

我正在尝试更改我在网上找到的这个脚本 https://pressstart.vip/tutorials/2018/09/25/58/spawning-obstacles.html 以使用正交相机,因为我的游戏就是这样使用的。目前它只适用于透视相机,我真的不知道它是如何工作的,因为我还没有真正接触过相机矩阵。这是脚本的代码:

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();
        }
    }
}

我的目标是更改脚本以使其与正交相机一起正常工作。 (缩进乱七八糟,这不是问题)。

出于某种原因,代码使用 Camera.main.transform.position.z 作为相机深度组件。在 2d 游戏的典型相机设置中,此值将为负数。

所以它是通过跟随相机后面的平截头体的右边缘来找到屏幕的左侧。很奇怪。如果它是正交的,你不能沿着截锥体的右侧找到屏幕左侧的位置,所以它不起作用也就不足为奇了。

相反,只需使用平截头体的左侧并通过取反该分量使深度为正:

screenBounds = Camera.main.ViewportToWorldPoint(
        new Vector3(0f, 0f, -Camera.main.transform.position.z));