Skip to content

Instantly share code, notes, and snippets.

@kleberandrade
Created September 4, 2019 19:46
Show Gist options
  • Save kleberandrade/fa293270a2661a8868e5cf48bc7fff2a to your computer and use it in GitHub Desktop.
Save kleberandrade/fa293270a2661a8868e5cf48bc7fff2a to your computer and use it in GitHub Desktop.
using System.Collections;
using UnityEngine;
public class CameraShake : MonoBehaviour
{
public static CameraShake Instance { get; private set; }
public void Awake()
{
if (Instance != null)
{
Destroy(gameObject);
}
else
{
Instance = this;
}
}
public void ShakeOnce(float duration, float magnitude)
{
StartCoroutine(Shake(duration, magnitude));
}
private IEnumerator Shake(float duration, float magnitude)
{
Vector3 originalPosition = transform.position;
float elapsedTime = 0.0f;
while (elapsedTime < duration)
{
Vector3 position = Random.insideUnitSphere * magnitude * Time.deltaTime;
transform.position = originalPosition + position;
elapsedTime += Time.deltaTime;
yield return null;
}
transform.localPosition = originalPosition;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment