關於計算透視投影的四條邊的方法,留做備忘

因爲項目須要,要計算出透視模式攝像機的四條外邊。簡直就是作數學題啊,尼瑪,不過還好,最終是寫出來了!this

using UnityEngine;
using System.Collections;

public class ClassA : MonoBehaviour
{

    public float distance;
	// Use this for initialization
	void Start () {
	
	}
	
	// Update is called once per frame
	void Update () {
	
	}
    void OnDrawGizmos()
    {
        DrawVectors();
    }
    public void DrawVectors()
    {
        var cameraMain = Camera.main;
        var cameraMainTran = cameraMain.transform;
        var forward = cameraMain.transform.forward;
        var angleVerticalTan = Mathf.Tan(Camera.main.fieldOfView/2*Mathf.Deg2Rad);
        var angleHorizontalTan = angleVerticalTan*cameraMain.aspect;
        var halfVerticalVector = cameraMainTran.up * angleVerticalTan;
        var halfHorizontalVector = cameraMainTran.right * angleHorizontalTan;
        var vec1 = forward + halfVerticalVector + haleHorizontalVector;
        var vec2 = forward + halfVerticalVector - haleHorizontalVector;
        var vec3 = forward - halfVerticalVector - halfHorizontalVector;
        var vec4 = forward - halfVerticalVector + halfHorizontalVector;
        Gizmos.color = Color.red;
        Gizmos.DrawLine(cameraMainTran.position, cameraMainTran.position + vec1 * 1500);
        Gizmos.color = Color.blue;
        Gizmos.DrawLine(cameraMainTran.position, (cameraMainTran.position + vec2 * 1500));
        Gizmos.color = Color.yellow;
        Gizmos.DrawLine(cameraMainTran.position, cameraMainTran.position + vec3 * 1500);
        Gizmos.color = Color.green;
        Gizmos.DrawLine(cameraMainTran.position, cameraMainTran.position + vec4 * 1500);
    }
} 

  最終效果是這樣的orm

時間匆忙,註釋後續再補!blog

相關文章
相關標籤/搜索