Created
September 7, 2016 18:36
-
-
Save Pyredrid/eb02f62d4e05ff0efac757d23fc36379 to your computer and use it in GitHub Desktop.
A modified version of the SmoothLookAt script found on the Unity3D wiki: http://wiki.unity3d.com/index.php/SmoothLookAt_CS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using System.Collections; | |
public class SmoothLookAt : MonoBehaviour { | |
public Transform target; | |
public float distance = 10.0f; | |
public float height = 5.0f; | |
//Animation curves to adjust the smoothing of | |
//the transform's overall movement | |
public AnimationCurve rotationDampingCurve; | |
public AnimationCurve heightDampingCurve; | |
//The overall speeds at which the above curves | |
//happen, 0.5 takes 2 seconds to complete | |
//the above curves, 2.0 takes half a second | |
//to complete the above curves | |
public float rotationDampingSpeed = 1.0f; | |
public float heightDampingSpeed = 1.0f; | |
void Start () { | |
Debug.Assert(target != null); | |
} | |
void LateUpdate () { | |
// Calculate the current rotation angles | |
float targetRotationAngle = target.eulerAngles.y; | |
float targetHeight = target.position.y + height; | |
float currentRotationAngle = transform.eulerAngles.y; | |
float currentHeight = transform.position.y; | |
// Calculate the damping amounts | |
float diffAngle = Quaternion.Angle(target.rotation, transform.rotation); | |
float rotationDamping = rotationDampingCurve.Evaluate(diffAngle); | |
float heightDamping = Mathf.Clamp01(Mathf.Abs(targetHeight - currentHeight)); | |
heightDamping = heightDampingCurve.Evaluate(heightDamping); | |
// Damp the rotation around the y-axis | |
currentRotationAngle = Mathf.LerpAngle(currentRotationAngle, targetRotationAngle, rotationDamping * (Time.deltaTime * rotationDampingSpeed)); | |
// Damp the height | |
currentHeight = Mathf.Lerp(currentHeight, targetHeight, heightDamping * (Time.deltaTime * heightDampingSpeed)); | |
// Convert the angle into a rotation | |
Quaternion currentRotation = Quaternion.Euler(0, currentRotationAngle, 0); | |
// Set the position of the camera on the x-z plane to: | |
// distance meters behind the target | |
transform.position = target.position; | |
transform.position -= currentRotation * Vector3.forward * distance; | |
// Set the height of the camera | |
transform.position = new Vector3(transform.position.x, currentHeight, transform.position.z); | |
// Always look at the target | |
transform.LookAt(target); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment