Skip to content

Instantly share code, notes, and snippets.

@AntipodeYarns
Created December 21, 2022 10:05
Show Gist options
  • Save AntipodeYarns/ca8504779c367e1006bd52dec1344e74 to your computer and use it in GitHub Desktop.
Save AntipodeYarns/ca8504779c367e1006bd52dec1344e74 to your computer and use it in GitHub Desktop.
Unity Camera Follow script to track a moving player object where camera rotation
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unity;
public class CameraFollow : MonoBehaviour
{
public Vector3 offset;
public Transform target;
public float lerpInterval;
public void LateUpdate()
{
var current = transform.position;
var _velocity = target.GetComponent<Rigidbody>().velocity;
_velocity.y = 0; // Cancels velocity in the vertical axis.
//stores the flat velocity of your player so it can put the camera always behind it
float targetAngle = Quaternion.LookRotation(_velocity).eulerAngles.y;
// Zeroes out rotations in the XY and YZ planes, to isolate rotation in the XZ (i.e. around the Y) plane.
var cameraRotation = Quaternion.Euler(0, targetAngle, 0);
// Allows user to configure smoothing factor for janky camera movements. This bit isn't perfect yet.
transform.position = Vector3.Lerp(current, target.transform.position + (cameraRotation * offset), lerpInterval);
transform.LookAt(target.transform);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment