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
MediumLet the player fly the camera around the tower.
- In
Update(), the right and left arrows changeyawatturnSpeed, and up and down changepitchattiltSpeed, timesTime.deltaTime. - Then keep
pitch = Mathf.Clamp(pitch, 10f, 60f);. - In
LateUpdate(), settransform.position = target.position + Quaternion.Euler(pitch, yaw, 0) * new Vector3(0, 0, -distance);, thentransform.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
1Rigidbody
Gravity and MassPush with AddForceJump with an ImpulseFixedUpdate for PhysicsVelocityKinematic BodiesRecap: Launch Pad4Coroutines
InvokeInvokeRepeating, CancelInvokeYour First CoroutineLoops in CoroutinesStopping CoroutinesRecap: Countdown10Project: Arena Escape
The ArenaHunters2Collisions
OnCollisionEnterWhat Did I Hit?Break on ImpactStanding on the GroundBounce and FrictionCollider ShapesRecap: Breakable WallPractice on your own: Unity playground