I have world coordinates for the GameObject object and for Camera.main, and I would like to calculate the position and rotation relative to Camera.main.
Position is easy:
object.transform.position - Camera.main.transform.position 
How to calculate Quaternion for given object relative to camera?
I can set object.transform.parent = Camera.main.transform and read localRotation, but is there more elegant solution.
By definition:
obj.transform.parent.rotation * obj.transform.localrotation = obj.transform.rotation
So, another way of phrasing your question is that you want to find the quaternion q such that Camera.main.transform.rotation * q == object.transform.rotation. So, you can solve this algebraically:
cam_rotation * q = obj_rotation inverse(cam_rotation) * cam_rotation * q = inverse(cam_rotation) * obj_rotation q = inverse(cam_rotation) * obj_rotation
And to calculate that in unity:
Quaternion q = Quaternion.Inverse(Camera.main.transform.rotation) 
               * object.transform.rotation;
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With