Rotate around moving object using only code

Hey everybody !

I am trying to get an orbit of my camera around a moving object only using code, I would like to use transform.RotateAround as it seems it is a pretty straight forward solution

For now I have this :

    void LateUpdate()
    {
            MouseInput = new Vector2(Input.GetAxisRaw("Mouse X"), Input.GetAxisRaw("Mouse Y"));
            Vector3 offset = new Vector3 (cameraPivot.position.x + cameraOffset.x, cameraPivot.position.y + cameraOffset.y, cameraPivot.position.z + cameraOffset.z);

        
            transform.position =offset;

            transform.RotateAround(cameraPivot.position, cameraPivot.up, MouseInput.x);
            transform.RotateAround(cameraPivot.position, cameraPivot.right, MouseInput.y);

    }

The camera does follow the object when moving, but the rotation is happening on the camera itself( like its looking around ) but not around the object.
Note that this is not happening when I dont update the transform.position of the camera, and the camera is orbiting correctly the object in that case.

any idea what could cause that ?

Thank you !

You can get it with trigonometry:

position.x = center.x + radius * cos(angle)
position.z = center.z + radius * sin(angle)

Center is the position of the object, radius the distance from it to the camera. Changing angle will move the camara around the object and you can orient it with Transform.LookAt function.

Not sure if this could be done even easier with atan2.

1 Like

It is working just fine with this indeed, thanks a lot @JesusMartinPeregrina
Here is the code if someone needs it at somepoint :

angle += (-Input.GetAxisRaw("Mouse X")) * 0.1f;
angleY += Input.GetAxisRaw("Mouse Y") * 0.1f;

position = cameraPivot.position;
Vector3 center = cameraPivot.position;
position.x = center.x + 10f * Mathf.Cos(angle);
position.z = center.z + 10f * Mathf.Sin(angle);
position.y = center.y + 10f * Mathf.Sin(angleY);
transform.position = position;
transform.LookAt(cameraPivot.position, Vector3.up);

If someone has any idea on how to solve this with transform.RotateAround I will be curious to see what was wrong ?