Skip to content

Instantly share code, notes, and snippets.

@mattmccray
Created October 18, 2017 17:24
Show Gist options
  • Save mattmccray/21ae648ae3d0d649f7c4c6f2d936d8b4 to your computer and use it in GitHub Desktop.
Save mattmccray/21ae648ae3d0d649f7c4c6f2d936d8b4 to your computer and use it in GitHub Desktop.
Camera Shake
using UnityEngine;
using System.Collections;
public class CameraShake : MonoBehaviour
{
public static CameraShake instance;
private Vector3 _originalPos;
private float _timeAtCurrentFrame;
private float _timeAtLastFrame;
private float _fakeDelta;
void Awake()
{
instance = this;
}
void Update()
{
// Calculate a fake delta time, so we can Shake while game is paused.
_timeAtCurrentFrame = Time.realtimeSinceStartup;
_fakeDelta = _timeAtCurrentFrame - _timeAtLastFrame;
_timeAtLastFrame = _timeAtCurrentFrame;
}
public static void Shake(float duration, float amount)
{
instance._originalPos = instance.gameObject.transform.localPosition;
instance.StopAllCoroutines();
instance.StartCoroutine(instance.cShake(duration, amount));
}
public IEnumerator cShake(float duration, float amount)
{
float endTime = Time.time + duration;
while (duration > 0)
{
transform.localPosition = _originalPos + Random.insideUnitSphere * amount;
duration -= _fakeDelta;
yield return null;
}
transform.localPosition = _originalPos;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment