# Camera rotate around gameobject

Hi everyone,

I’ve been working on a script which would allow my player to rotate the camera around a gameobject serving as a centerpoint.

Here’s the script I’ve been doing so far using C# and a reduced script based from MouseLook.cs:

public class PlayerCamera : MonoBehaviour
{
public enum RotationAxes { MouseXAndY = 0, MouseX = 1, MouseY = 2 }
public RotationAxes axes = RotationAxes.MouseXAndY;
public float sensitivityX = 15F;

``````public float minimumX = -360F;
public float maximumX = 360F;

public float speed = 60;

public Transform RotationCenter;

float rotationY = 0F;

void Update ()
{
if(Input.GetKey(KeyCode.LeftControl))
{
transform.Rotate(0, Input.GetAxis("Mouse X") * sensitivityX, 0);
}

}

void Start ()
{
// Make the rigid body not change rotation
if (rigidbody)
rigidbody.freezeRotation = true;
}
``````

}

I know the RotateAround function exists, but I’ve yet to find a solution and that’s why I’d need your help.

Thank you!

I’ve got an answer for this problem, but it provokes another problem.

First of all, here’s the script i’ve completed:

using UnityEngine;
using System.Collections;

public class RotateCamera : MonoBehaviour
{
public Transform target;

``````private float distance;

public float xSpeed = 250;

private float x = 0;
private float y = 0;

void Start()
{
distance = Vector3.Distance(transform.position, target.position);

var angles = transform.eulerAngles;

x = angles.y;
y = angles.x;

if(rigidbody)
{
rigidbody.freezeRotation = true;
}
}

void LateUpdate()
{
if(target && Input.GetKey(KeyCode.LeftControl))
{
x += Input.GetAxis("Mouse X") * xSpeed * 0.02f;

var rotation = Quaternion.Euler(0, 0, 0);

var position = rotation * (new Vector3(0, 0, -distance)) + target.position;

transform.rotation = rotation;

transform.position = position;
}
}
``````

}

It does a nice job up to now. But, in game, when I press the CTRL button, my camera goes down on the Y axis even if I don’t ask it to do so.

Anybody has a clue why?

var target : Transform;
var distance = 10.0;

var xSpeed = 250.0;
var ySpeed = 120.0;

var yMinLimit = -20;
var yMaxLimit = 80;

private var x = 0.0;
private var y = 0.0;

function Start () {
var angles = transform.eulerAngles;
x = angles.y;
y = angles.x;

``````// Make the rigid body not change rotation
if (rigidbody)
rigidbody.freezeRotation = true;
``````

}

function LateUpdate () {
if (target) {
x += Input.GetAxis(“Mouse X”) * xSpeed * 0.02;
y -= Input.GetAxis(“Mouse Y”) * ySpeed * 0.02;

``````	y = ClampAngle(y, yMinLimit, yMaxLimit);

var rotation = Quaternion.Euler(y, x, 0);
var position = rotation * Vector3(0.0, 0.0, -distance) + target.position;

transform.rotation = rotation;
transform.position = position;
}
``````

}

static function ClampAngle (angle : float, min : float, max : float) {
if (angle < -360)
angle += 360;
if (angle > 360)
angle -= 360;
return Mathf.Clamp (angle, min, max);
}