Created
October 2, 2016 15:34
-
-
Save MrMatthias/24396f51c4ec710e967dbb35e5ded281 to your computer and use it in GitHub Desktop.
Unity face camera, keep up direction
This file contains 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; | |
[ExecuteInEditMode] | |
public class FaceCamera : MonoBehaviour | |
{ | |
public bool faceCameraActive = true; | |
public Camera targetCamera; | |
public float rotateSpeed = 1.0f; | |
// Use this for initialization | |
void Start () | |
{ | |
if (targetCamera == null) { | |
targetCamera = Camera.main; | |
} | |
} | |
void Update () | |
{ | |
if (!faceCameraActive) { | |
return; | |
} | |
Vector3 localCamPosition = transform.InverseTransformPoint (targetCamera.transform.position); | |
localCamPosition = new Vector3 (localCamPosition.x, 0, localCamPosition.z); | |
Vector3 lookTarget = transform.TransformPoint (localCamPosition); | |
Vector3 targetDirection = (lookTarget - transform.position).normalized; | |
//transform.LookAt (lookTarget, transform.up); | |
Quaternion tr = Quaternion.LookRotation (lookTarget, transform.up); | |
transform.rotation = Quaternion.Slerp (transform.rotation, tr, Time.deltaTime * rotateSpeed); | |
} | |
public void OnDrawGizmos () | |
{ | |
Vector3 localCamPosition = transform.InverseTransformPoint (targetCamera.transform.position); | |
localCamPosition = new Vector3 (localCamPosition.x, 0, localCamPosition.z); | |
Vector3 lookTarget = transform.TransformPoint (localCamPosition); | |
Vector3 targetDirection = (lookTarget - transform.position).normalized; | |
Gizmos.color = Color.red; | |
Gizmos.DrawSphere (transform.position + targetDirection, 0.01f); | |
Gizmos.DrawCube (lookTarget, Vector3.one * 0.03f); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment