Skip to content

Instantly share code, notes, and snippets.

@brettmjohnson
Created June 13, 2016 19:40
Show Gist options
  • Save brettmjohnson/64d8e41005267c4b92a5ba4f3b2a787a to your computer and use it in GitHub Desktop.
Save brettmjohnson/64d8e41005267c4b92a5ba4f3b2a787a to your computer and use it in GitHub Desktop.
using UnityEngine;
using System.Collections;
// On first-person controllers, the camera and body are separate objects,
// so to perform a smooth look-at, they must rotate along different axes, in unison.
// NOTE: You will likely have to disable the look/camera controller in order for this to work.
public class FirstPersonLookAt : MonoBehaviour
{
public Transform body;
public Transform camera;
public Transform target;
public float speed = 5f;
public Vector3 offset;
public bool follow;
void Update ()
{
if (target != null)
{
// rotate body around y-axis
Vector3 direction = (target.position + offset) - body.position;
direction.y = 0; // forces rotation around y-axis
Quaternion bodyRotation = Quaternion.LookRotation(direction);
body.rotation = Quaternion.Slerp(body.rotation, bodyRotation, speed * Time.deltaTime);
// rotate camera around x-axis locally
direction = (target.position + offset) - camera.position;
Quaternion cameraRotation = Quaternion.Inverse(bodyRotation) * Quaternion.LookRotation(direction); // get difference of rotations to limit to x-axis local rotation
camera.localRotation = Quaternion.Slerp(camera.localRotation, cameraRotation, speed * Time.deltaTime);
// stop when target reached, unless set to follow
if (!follow)
{
if (Quaternion.Angle(camera.localRotation, cameraRotation) < 0.1f
&& Quaternion.Angle(body.rotation, bodyRotation) < 0.1f)
{
target = null; // reset target and stop
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment