Monday, January 19, 2015

Unity: Orbit a camera around any point in a scene

To orbit a camera around any point in a scene, Create a C# script and attach it to the main camera in your scene. In the script's LateUpdate() method, put the following codes. The code enables user to orbit the camera around a target point (which is in the demo code, but you can set it to any point, even point that is moving) when he holds down the Ctrl key and hold down and drag the mouse.

public float RotateAmount = 15f;

void LateUpdate()

public void OrbitCamera()
 bool isCtrlKeyDown = Input.GetKey(KeyCode.LeftControl) || Input.GetKey(KeyCode.RightControl);
 if (isCtrlKeyDown && Input.GetMouseButton(0))
  Vector3 target =; //this is the center of the scene, you can use any point here
  float y_rotate = Input.GetAxis("Mouse X") * RotateAmount;
  float x_rotate = Input.GetAxis("Mouse Y") * RotateAmount;
  OrbitCamera(target, y_rotate, x_rotate);

public void OrbitCamera(Vector3 target, float y_rotate, float x_rotate)
 Vector3 angles = transform.eulerAngles;
 angles.z = 0;
 transform.eulerAngles = angles;
 transform.RotateAround(target, Vector3.up, y_rotate);
 transform.RotateAround(target, Vector3.left, x_rotate);


No comments:

Post a Comment