Menu
CoddyTech

Orbit Camera

Part of the Physics and Gameplay section of Coddy's Unity journey. Lesson 48 of 71.

To circle around a point, keep an angle, turn a fixed offset by it and add the result to the point. Rotation times vector does the turning: Quaternion.Euler(0, angle, 0) * offset swings the offset around the y axis, and its length and height stay the same. This camera circles a statue at 20 degrees per second, always 3 units up and 6 out:

public Transform statue;
public float speed = 20f;
float angle;

void LateUpdate()
{
    angle += speed * Time.deltaTime;
    Vector3 offset = new Vector3(0, 3, -6);
    transform.position = statue.position + Quaternion.Euler(0, angle, 0) * offset;
    transform.LookAt(statue);
}

At angle 0 the offset is (0, 3, -6), so the camera is behind the statue. At 90 it is (-6, 3, 0), on the statue's -x side, and at 180 it is (0, 3, 6), in front. Moving the camera does not turn it, so LookAt aims it back at the statue from each new spot.

A second angle raises the camera: Quaternion.Euler(pitch, yaw, 0) * new Vector3(0, 0, -distance) turns the back direction up by pitch (a positive turn around x tips (0, 0, -1) upward) and then around by yaw, so the camera stays distance away at any angle.

The angle lives in your own field, as in Euler Angles: it can grow past 360 or drop below 0 with no jump, and you can clamp it or change it from the keyboard. Doing this in LateUpdate() places the camera after the statue, or a player, has moved for the frame.

challenge icon

Challenge

Medium

Let the player fly the camera around the tower.

  1. In Update(), the right and left arrows change yaw at turnSpeed, and up and down change pitch at tiltSpeed, times Time.deltaTime.
  2. Then keep pitch = Mathf.Clamp(pitch, 10f, 60f);.
  3. In LateUpdate(), set transform.position = target.position + Quaternion.Euler(pitch, yaw, 0) * new Vector3(0, 0, -distance);, then transform.LookAt(target);.

Press Play and fly around the tower. Then Check.

Try it yourself

using UnityEngine;

public class OrbitCamera : MonoBehaviour
{
    public Transform target;
    public float distance = 8f;
    public float turnSpeed = 90f;
    public float tiltSpeed = 45f;
    public float yaw = 0f;
    public float pitch = 30f;

    void Update()
    {
        // Arrows change yaw and pitch.
    }

    void LateUpdate()
    {
        // Place the camera around the target and look at it.
    }
}

All lessons in Physics and Gameplay

Practice on your own: Unity playground