Created
April 23, 2016 17:49
-
-
Save codemaster/5c2cf21c80fd2b4f72d5af4b3d562d1c to your computer and use it in GitHub Desktop.
Unity Script that shakes the camera!
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; | |
//! Script that shakes the camera | |
public class CameraShake : MonoBehaviour | |
{ | |
//! The amplitude/strength of the shake. | |
//! Higher values shake the camera harder. | |
public float shakeAmplitude = 0.7f; | |
//! Dampen is how fast our shake stops. Default is 1. | |
public float dampenFactor = 1.0f; | |
//! The cache for this object's transform component | |
private Transform _transformCache; | |
//! The original location of this objcet before a shake | |
private Vector3 _originalPos; | |
//! How long to shake for. | |
private float _shakeDuration = 0f; | |
//! Runs when the object is created | |
private void Awake() | |
{ | |
// Cache the transform position | |
_transformCache = GetComponent<Transform>(); | |
} | |
//! Shake the camera during our UI/late update | |
private void LateUpdate() | |
{ | |
// If we have shaking left to do | |
if (_shakeDuration > 0f) | |
{ | |
// Update our local position to our original position | |
// plus a randomized location inside a sphere that is | |
// the size of our amplitude | |
_transformCache.localPosition = _originalPos + | |
(Random.insideUnitSphere * shakeAmplitude); | |
// Reduce our shake time by the amount of time that has passed | |
// times our dampen factor | |
_shakeDuration -= Time.deltaTime * dampenFactor; | |
} | |
// No shaking left | |
else | |
{ | |
// Ensure our duration is reset | |
_shakeDuration = 0f; | |
// Reset our local position back to its original location | |
_transformCache.localPosition = _originalPos; | |
} | |
} | |
//! Shakes the camera! | |
//! @param[in] duration the Duration of the shake | |
public void Shake(float duration) | |
{ | |
// Hold onto the original position of the camera | |
_originalPos = _transformCache.localPosition; | |
// Set our duration of the shake | |
_shakeDuration = duration; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment