Menu
CoddyTech

Orbit Camera

Part of the Physics and Gameplay section of Coddy's Unity journey. Lesson 46 of 63.

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.

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, always distance (8) units from the tower's position and always looking at it. The script keeps two angles in yaw and pitch:

  • yaw is how far the camera has swung around the tower. The right arrow raises it and the left arrow lowers it, at turnSpeed (90) degrees per second. At yaw 0 the camera is on the tower's -z side; at yaw 90 it is on the -x side.
  • pitch is how many degrees the camera is raised above the tower's level, seen from the tower. The up arrow raises it and the down arrow lowers it, at tiltSpeed (45) degrees per second, and it stays between 10 and 60.

It starts at yaw 0 and pitch 30, which puts it 4 units above the tower's position and 6.93 behind it. Press Play, fly around, 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.
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Physics and Gameplay