美文网首页
获取摄像机的视口区域

获取摄像机的视口区域

作者: OneMore2018 | 来源:发表于2017-08-02 15:01 被阅读21次

    先上代码
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;

    public class test : MonoBehaviour {

    private Camera theCamera;
    
    public float distance = 8.5f;
    private Transform tran;
    void Start () {
    
        if(!theCamera)
        {
            theCamera = Camera.main;
        }
        //float temp = (float)Screen.width  /(float) Screen.height;
        //Debug.Log(temp);
        //Debug.Log(theCamera.aspect ); 
        tran = theCamera.transform;
      //  Debug.Log(theCamera.aspect); 
    }
    
    void Update () {
        FindCorners();
    }
    
    void FindCorners()
    {
        Vector3[] corner = GetCorners(distance);
    
        Debug.DrawLine(corner[0],corner[1],Color.red);
        Debug.DrawLine(corner[1], corner[3], Color.red);
        Debug.DrawLine(corner[3], corner[2], Color.red);
        Debug.DrawLine(corner[2], corner[0], Color.red);
    }
    
    Vector3[] GetCorners(float tempDistance)
    {
        Vector3[] corners = new Vector3[4];
        //  角度转化为弧度(照相机视野的一半)
        float halfOV = (theCamera.fieldOfView * 0.5f) * Mathf.Deg2Rad;
        Debug.Log(halfOV);
        float aspect = theCamera.aspect;
        //  这里算出来的宽和高都是视口矩形的一半
        float height = tempDistance * Mathf.Tan(halfOV);
    
        float width = height * aspect;
    
        // 左上
        corners[0] = tran.position - (tran.right * width);
        corners[0] += tran.up * height;
        corners[0] += tran.forward * tempDistance;
    
        // 右上
        corners[1] = tran.position + (tran.right * width);
        corners[1] += tran.up * height;
        corners[1] += tran.forward * tempDistance;
    
        // 左下
        corners[2] = tran.position - (tran.right * width);
        corners[2] -= tran.up * height;
        corners[2] += tran.forward * tempDistance;
    
        // 右下
        corners[3] = tran.position + (tran.right * width);
        corners[3] -= tran.up * height;
        corners[3] += tran.forward * tempDistance;
    
        return corners;
    
    }
    

    }

    运行结果如下

    Paste_Image.png

    这样就知道了摄像机的视口区域,接下来想做一些视口坐标的操作就简单了

    相关文章

      网友评论

          本文标题:获取摄像机的视口区域

          本文链接:https://www.haomeiwen.com/subject/ouzelxtx.html