Last active
January 26, 2018 22:41
-
-
Save ShacharWeis/5e6ab67839feac9729a24e4b6da01346 to your computer and use it in GitHub Desktop.
A stabilized object for Unity3D. Put a camera on it and it becomes a gimbal. Useful for recording user POV in VR.
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; | |
public class StabilizedObject : MonoBehaviour | |
{ | |
public Transform Parent; // Transform to track rotation | |
public bool SmoothPan = true; | |
public bool SmoothRoll = true; | |
public bool SmoothTilt = true; | |
public float SmoothingMinimum = 0.05f; | |
public float SmoothingMaximum = 0.005f; | |
public bool AutoLevel = true; | |
public bool AllowTilt = true; | |
private Quaternion lastRotation; | |
private Vector3 lastPosition; | |
private void SmoothRotation() | |
{ | |
float a = Quaternion.Angle(lastRotation, Parent.rotation); | |
float f = Mathf.InverseLerp(0, 1, a); | |
float smoothing = Mathf.Lerp(SmoothingMaximum,SmoothingMinimum , f); | |
Quaternion newRotation = Quaternion.Slerp(lastRotation, Parent.rotation, smoothing); | |
Vector3 rotationEuler = transform.rotation.eulerAngles; | |
Vector3 newRotationEuler = newRotation.eulerAngles; | |
if (SmoothRoll) rotationEuler.z = newRotationEuler.z; | |
if (AutoLevel) rotationEuler.z = 0; | |
if (SmoothTilt) rotationEuler.x = newRotationEuler.x; | |
if (!AllowTilt) rotationEuler.x = 0; | |
if (SmoothPan) rotationEuler.y = newRotationEuler.y; | |
transform.rotation = Quaternion.Euler(rotationEuler); | |
lastRotation = transform.rotation; | |
} | |
private void SmoothPosition() | |
{ | |
if (Vector3.Distance(lastPosition, Parent.position) > 0.2) | |
transform.position = Parent.position; // This means teleport (probably) | |
else | |
transform.position = Vector3.Lerp(lastPosition, Parent.position, 0.8f); | |
} | |
void Start() | |
{ | |
if (Parent == null) | |
Parent = gameObject.transform.parent.transform; | |
gameObject.transform.parent = null; | |
lastRotation = Parent.rotation; | |
lastPosition = Parent.position; | |
} | |
void Update() | |
{ | |
SmoothRotation(); | |
SmoothPosition(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment