Created
October 17, 2018 06:57
-
-
Save yoeven/ac733db2b9deb284ed47c6c78bbaee81 to your computer and use it in GitHub Desktop.
A simple camera shake that just shakes the camera from its current rotation and resets it back to its original location. Forked from http://wiki.unity3d.com/index.php/Camera_Shake
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 System.Collections; | |
using System.Collections.Generic; | |
using UnityEngine; | |
public class SimpleCameraShake : MonoBehaviour | |
{ | |
public static SimpleCameraShake Instance; | |
float shakeAmount; | |
float shakeDuration; | |
float shakePercentage; | |
float startAmount; | |
float startDuration; | |
bool isRunning = false; | |
bool smooth; | |
float smoothAmount = 5f; | |
private void Awake() | |
{ | |
if (Instance == null) | |
{ | |
Instance = this; | |
} | |
else if (Instance != this) | |
{ | |
Destroy(this); | |
} | |
} | |
public void ShakeCamera(float amount, float duration, bool _smooth = true, float _smoothAmount = 5f) | |
{ | |
shakeAmount += amount; | |
startAmount = shakeAmount; | |
shakeDuration += duration; | |
startDuration = shakeDuration; | |
smooth = _smooth; | |
smoothAmount = _smoothAmount; | |
if (!isRunning) StartCoroutine(Shake()); | |
} | |
IEnumerator Shake() | |
{ | |
isRunning = true; | |
Quaternion startingRotation = transform.localRotation; | |
while (shakeDuration > 0.01f) | |
{ | |
Vector3 rotationAmount = Random.insideUnitSphere * shakeAmount; | |
rotationAmount.z = 0; | |
shakePercentage = shakeDuration / startDuration; | |
shakeAmount = startAmount * shakePercentage; | |
shakeDuration = Mathf.Lerp(shakeDuration, 0, Time.deltaTime); | |
Quaternion roateTo = Quaternion.Euler(startingRotation.eulerAngles + rotationAmount); | |
if (smooth) | |
transform.localRotation = Quaternion.Lerp(transform.localRotation, roateTo, Time.deltaTime * smoothAmount); | |
else | |
transform.localRotation = roateTo; | |
yield return null; | |
} | |
transform.localRotation = startingRotation; | |
isRunning = false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment