Skip to content

Instantly share code, notes, and snippets.

@jgonzosan
Last active January 10, 2021 00:46
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jgonzosan/18ee2fafd930a0242d2fdeee7cd6560b to your computer and use it in GitHub Desktop.
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.
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