3D rotation around rotating object

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Andrea

I’m trying to set up a camera that freely move around a 3D object while looking at it, using the mouse x/y movement.
So i set the camera as a child of a spatial (called Rig), the camera is looking at the object at a certain distance but it is not directly moved, the rig instead rotates around the object.

Object

Rig

Camera

Below you can find the core of the code:

if event is InputEventMouseMotion:
   $Rig.rotate($Rig.global_transform.basis.y, event.speed.x/10000)
   $Rig.rotate($Rig.global_transform.basis.z, event.speed.y/10000)

it works as intended when the object is at rest on the original position (with no applied rotation), but as soon as the object is rotated it goes crazy, although i dont understand why since i’m telling the rig to rotate around its own axis, and from the camera point of view it should always look stationary indipendently from the rotation of the object (and therefore the same x-y mouse movement should translate in the same camera movement around the object)

What am i doing wrong?

:bust_in_silhouette: Reply From: Andrea

i just needed to orthonormalize the transform after the rotation.
Also, for reasons that are related to magic, is better to have y rotation before of the x rotation.

if event is InputEventMouseMotion:
 $Rig.rotate($Rig.transform.basis.z, event.speed.y/10000)
 $Rig.rotate($Rig.transform.basis.y, -event.speed.x/10000)
 $Rig.orthonormalize()