簡體   English   中英

在Unity3D中將點從世界轉換為相機空間

[英]Convert a point from world to camera space in Unity3D

我想將世界坐標( P_w )中的點轉換為相機坐標( P_c )。

這樣做,我第一次來翻譯P_w由負攝像機位置(在世界坐標C_pos ),之后轉動P_w - C_pos X繞X軸度,Y度繞Y軸和Z度繞Z軸。

我在Unity中編寫了此功能來做到這一點:

static public Vector4 convertWorldToCameraCoordinatesByDegrees (Vector3 point, PhotoData photoData)
{
    // translate the point by the negative camera-offset 
    //and convert to Vector4
    Vector4 translatedPoint = point - photoData.cameraPosition;
    // by default translatedPoint.w is 0
    translatedPoint.w = 1.0f;       

    // create rotation matrices
    Matrix4x4 rotationMatrixX = Matrix4x4.identity;
    Matrix4x4 rotationMatrixY = Matrix4x4.identity;
    Matrix4x4 rotationMatrixZ = Matrix4x4.identity;

    // setup rotationMatrixX
    rotationMatrixX.SetRow (1, 
        new Vector4 (0,
            Mathf.Cos (photoData.rotation.x),
            - Mathf.Sin (photoData.rotation.x),
            0));
    rotationMatrixX.SetRow (2,
        new Vector4 (0,
            Mathf.Sin (photoData.rotation.x),
            Mathf.Cos (photoData.rotation.x),
            0));

    // setup rotationMatrixY
    rotationMatrixY.SetRow (0, 
        new Vector4 (Mathf.Cos (photoData.rotation.y),
             0,
             Mathf.Sin (photoData.rotation.y),
             0));
    rotationMatrixY.SetRow (2,
        new Vector4 (- Mathf.Sin (photoData.rotation.y),
            0,
            Mathf.Cos (photoData.rotation.y),
            0));                            

    // setup rotationMatrixZ
    rotationMatrixZ.SetRow (0, 
        new Vector4 (Mathf.Cos (photoData.rotation.z),
            - Mathf.Sin (photoData.rotation.z),
            0,
            0));
    rotationMatrixZ.SetRow (1,
        new Vector4 (Mathf.Sin (photoData.rotation.z),
            Mathf.Cos (photoData.rotation.z),
            0,
            0));

    // unity doc says z-x-y in this order
    Matrix4x4 rotationMatrix = rotationMatrixY * rotationMatrixX * rotationMatrixZ;

    Vector4 transformedPoint = rotationMatrix * translatedPoint;

    return transformedPoint;
}

但是結果與另一個函數不同,在另一個函數中,我使用攝像機的上,前,右矢量來構建我的旋轉矩陣。

PhotoData是一類,具有有關相機的一些信息,包括位置和旋轉。 PhotoData.rotation是一個Vector3 ,它使相機繞x,y和z軸旋轉為x,y,z值。

有人可以告訴我為什么這不起作用嗎?

//編輯:有些人提到了內置函數,但是我必須在不使用它們的情況下對其進行計算。 我忘了在原始帖子中寫它。 我首先用c ++編寫了該算法,並希望在Unity中對其進行測試,因為它更易於驗證。

查看您的代碼,以為您使簡單的任務復雜化了很多,否則我不明白這個問題。 您絕對可以使用Camera.WorldToScreenPoint

http://docs.unity3d.com/ScriptReference/Camera.WorldToScreenPoint.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM