用Unity3d的maxtrix实现的WolrdToScreen

来源:互联网 发布:2017年淘宝客市场规模 编辑:程序博客网 时间:2024/05/18 08:50

最近在使用Unity的转换矩阵的时候,遇到点问题,现在解决了,贴出来,大家有需要的可以拿走



using UnityEngine;




public class CameraTest : MonoBehaviour 
{
    void Start()
    {
        Vector3 p0 = new Vector3(0, 12.58f, 10);
        Vector3 screenP = Camera.main.WorldToScreenPoint(p0);
        Debug.Log(screenP);


        Matrix4x4 mvp = Camera.main.projectionMatrix * Camera.main.worldToCameraMatrix;
        Vector3 screenP1 = WorldToScreen(mvp, p0, Screen.width, Screen.height);
        Debug.Log(screenP1);
    }


    Vector3 WorldToScreen(Matrix4x4 camMVP, Vector3 point, float renderWidth, float renderHeight)
    {
        Vector3 result;
        result.x = camMVP.m00 * point.x + camMVP.m01 * point.y + camMVP.m02 * point.z + camMVP.m03;
        result.y = camMVP.m10 * point.x + camMVP.m11 * point.y + camMVP.m12 * point.z + camMVP.m13;
        result.z = camMVP.m20 * point.x + camMVP.m21 * point.y + camMVP.m22 * point.z + camMVP.m23;
        float num = camMVP.m30 * point.x + camMVP.m31 * point.y + camMVP.m32 * point.z + camMVP.m33;
        float oriNum = num;
        num = 1f / num;
        result.x *= num;
        result.y *= num;
        result.z = oriNum; // num contains the 1 / (distance to camera), ideal to linearly interpolate the depth in a rasterizer
        point = result;


        point.x = (point.x * 0.5f + 0.5f) * renderWidth;
        point.y = (point.y * 0.5f + 0.5f) * renderHeight;


        return point;
    }

}

0 0
原创粉丝点击