Created
April 4, 2013 09:37
-
-
Save N-Carter/5309096 to your computer and use it in GitHub Desktop.
Chase camera that works in any orientation
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 SuperChaseCamera : MonoBehaviour | |
{ | |
public Transform m_Target; | |
public Vector3 m_TargetOffset = new Vector3(0.0f, 1.0f, 0.0f); | |
public Vector3 m_ChasingOffset = new Vector3(0.0f, 1.0f, -10.0f); | |
public Vector3 m_LeadingOffset = new Vector3(0.0f, 1.0f, 20.0f); | |
public float m_NormalisingFactor = 0.1f; | |
protected Vector3 m_Position; | |
protected Vector3 m_Up; | |
protected Vector3 m_TargetPosition; | |
delegate void View(); | |
View m_View; | |
// Events: | |
protected void Start() | |
{ | |
m_View = ForwardView; | |
ResetView(); | |
} | |
protected void FixedUpdate() | |
{ | |
m_View(); | |
} | |
protected void Update() | |
{ | |
if(Input.GetButtonDown("Rear View")) | |
{ | |
if(m_View != ForwardView) | |
m_View = ForwardView; | |
else | |
m_View = RearView; | |
ResetView(); | |
} | |
else if(Input.GetButtonDown("Target View")) | |
{ | |
m_View = TargetView; | |
RaycastHit hit; | |
if(Physics.Raycast(m_Target.position, m_Target.forward, out hit)) | |
m_TargetPosition = hit.point; | |
else | |
m_TargetPosition = transform.forward * 10000.0f; | |
} | |
} | |
// Delegate methods: | |
protected void ForwardView() | |
{ | |
LerpTowardsTarget(m_ChasingOffset); | |
} | |
protected void RearView() | |
{ | |
LerpTowardsTarget(m_LeadingOffset); | |
} | |
protected void TargetView() | |
{ | |
Vector3 targetVector = (m_TargetPosition - m_Target.position).normalized; | |
transform.rotation = Quaternion.LookRotation(targetVector, m_Target.up); | |
transform.position = m_Target.position + transform.rotation * new Vector3(0.0f, 2.0f, -5.0f); | |
} | |
// Other methods: | |
protected void LerpTowardsTarget(Vector3 offset) | |
{ | |
m_Position = Vector3.Lerp(transform.position, m_Target.TransformPoint(offset), m_NormalisingFactor); | |
m_Up = Vector3.Lerp(transform.up, m_Target.up, m_NormalisingFactor); | |
m_TargetPosition = Vector3.Lerp(m_TargetPosition, m_Target.TransformPoint(m_TargetOffset), m_NormalisingFactor); | |
transform.position = m_Position; | |
transform.LookAt(m_TargetPosition, m_Up); | |
} | |
protected void ResetView() | |
{ | |
Vector3 offset = (m_View != ForwardView ? m_LeadingOffset : m_ChasingOffset); | |
m_Position = m_Target.TransformPoint(offset); | |
m_Up = transform.up; | |
m_TargetPosition = m_Target.position; | |
transform.position = m_Position; | |
transform.LookAt(m_TargetPosition, m_Up); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment