# Rotating a camera around a game object?

I tried to rotate the camera around an object in the game using trigonometry. But whenever the angle of any of the rotation coordinates goes above 90 degrees or below 270 the camera would quickly invert it’s position coordinates and instantly put its rotation back between 270 and 90.

I used the code below, I have no idea why it isn’t working.

``````	void Update () {
camera_rotX = transform.rotation.x;
camera_rotY = transform.rotation.y;
camera_rotZ = transform.rotation.z;
findPos ();
transform.position = new Vector3 (camera_posX, camera_posY, camera_posZ);
}

void findPos(){
camera_posX = (Mathf.Sin(camera_rotX)) * camera_distance;
camera_posY = (Mathf.Sin(camera_rotY)) * camera_distance;
camera_posZ = (Mathf.Sin(camera_rotZ)) * camera_distance;
}
``````

I have seen the “RotateAround” function being suggested, but wouldn’t a more mathematical solution allow better control over things like the distance between the object and camera?

I was hoping to use this code to make a camera setup similar to that of Homeworld, so the player can drag their mouse and pan the camera around the object they have it attached to.

Help! (And thanks!)

There’s two things you can do, if you don’t want to use RotateAround (which I still recommend)

1. Change the hierarchy of how you camera is set up so it’s child of a pivot point. Something like this:

L Pivot
L Camera
Set up like that, all you have to do is change the parent of Pivot to that of the object you want to rotate around, like so

pivot.transform.SetParent(target.transform)
Where target is whatever object you want to rotate around. Then all you have to do is rotate pivot and the camera will rotate around it. To change the distance, simply change the distance between Pivot and Camera, using Camera’s localPosition values

2. If you want to get extra mathematical, look into spherical coordinates and Quaternions. Should fix the problem right away.

Using @Arkaid 's solution I created the following C# script and added it as a component to the the pivot. Works great!

`````` public class PanAroundObject : MonoBehaviour {

[SerializeField]
Transform pivot;

void Start () {
pivot = transform;
}

void Update () {
pivot.Rotate(0,1,0);

}
}
``````