I want to convert a point in world coordinates ( P_w
) to camera coordinates ( P_c
).
To do so I first have to translate P_w
by the negative camera position (in world coordinates C_pos
) and after that rotate P_w - C_pos
x degrees around the x-axis, y degrees around the y-axis and z degrees around the z-axis.
I wrote this function in Unity to do this:
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;
}
But the results are different from another function where build my roations matrix using the up, forward and right vector of my camera.
PhotoData
is a class that has some information about the camera including the position and the rotation. PhotoData.rotation
is a Vector3
which has the camera rotation around the x, the y, and the z axis as x-, y-, z-values.
Can someone tell me why this is not working?
// edit: Some people have mentioned build-in functions, but I have to compute this with out them. I forgot to write it in the original post. I wrote this algorithm first in c++ and wanted to test it in Unity since it's easier to verify it.
Looking at your code and think you are massively overcomplicating simple task, or I do not understand the question. You can definitely use Camera.WorldToScreenPoint
http://docs.unity3d.com/ScriptReference/Camera.WorldToScreenPoint.html
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.