Last active
January 10, 2021 00:46
-
-
Save jgonzosan/18ee2fafd930a0242d2fdeee7cd6560b to your computer and use it in GitHub Desktop.
This script can be used to add shake to a camera in Unity. This is useful for explosions or erratic movements of the camera that can either be sustained or short.
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; | |
public class Shake : MonoBehaviour | |
{ | |
public float shakeDuration = 0f; | |
public float shakeAmount = 0.7f; | |
public float decreaseFactor = 1.0f; | |
public bool soloStart; | |
private float resetDuration; | |
private Transform camTransform; | |
Vector3 originalPos; | |
void Awake() | |
{ | |
camTransform = GetComponent<Transform>(); | |
} | |
void Start () | |
{ | |
originalPos = camTransform.localPosition; | |
resetDuration = shakeDuration; | |
if(soloStart){ | |
StartCoroutine("ExplosionShake"); | |
} | |
} | |
public void StartExplosionShake () | |
{ | |
StartCoroutine("ExplosionShake"); | |
} | |
IEnumerator ExplosionShake () | |
{ | |
while (shakeDuration > 0) | |
{ | |
camTransform.localPosition = originalPos + Random.insideUnitSphere * shakeAmount; | |
shakeDuration -= Time.deltaTime * decreaseFactor; | |
yield return new WaitForEndOfFrame(); | |
} | |
shakeDuration = resetDuration; | |
camTransform.localPosition = originalPos; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment