Search code examples
pythonunity-game-engine3d

How to convert from world coordinates to camera coordinates


In the world coordinate system, there are objects with rotation values rx1,ry1,rz1 and position values px1,py1,pz1.

Similarly, there is an camera in the world coordinate system with rotation values rx2,ry2,rz2 and position values px2,py2,pz2.

What formula can be used to convert rx1,ry1,rz1,px1,py1,pz1 to the camera coordinate system?

The up vector of the camera is the Y-axis, always oriented toward the object near the world origin.

The camera and the model are supposed to move within the range as shown in the following gif image. enter image description here

I would like to use Python to do the calculations, but I am open to any other answers, including other Unity C# or mathematical statements.

You are welcome to have commentary in quaternions or in matrices instead of euler angles.


Solution

  • Within Unity c# for the position you can simply use the built-in

    var localPosition = camera.transform.InverseTransformPoint(theObject.transform.position);
    

    for the rotation you can use

    var localRotation = Quaternion.Inverse(camera.transform.rotation) * theObject.transform.rotation;
    

    This should give you the localPosition and localRotation in the coordinate space of the camera.