Created
February 4, 2016 18:59
-
-
Save miguelSantirso/c0e6ed6291de7bb5629e to your computer and use it in GitHub Desktop.
[Unity] Easy Transform/Camera shaker
This file contains hidden or 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 TransformShaker : MonoBehaviour | |
{ | |
public Vector3 defaultDirection = new Vector3(0,1,0); | |
public float defaultSeconds = 0.3f; | |
public float defaultAmplitude = 0.05f; | |
public float defaultPeriod = 0.02f; | |
private Vector3 startPosition = Vector3.zero; | |
public IEnumerator Shake() | |
{ | |
yield return StartCoroutine(Shake(defaultDirection, defaultSeconds, defaultAmplitude, defaultPeriod)); | |
} | |
public IEnumerator Shake(Vector3 direction) | |
{ | |
yield return StartCoroutine(Shake(direction, defaultSeconds, defaultAmplitude, defaultPeriod)); | |
} | |
public IEnumerator Shake(Vector3 direction, float seconds) | |
{ | |
yield return StartCoroutine(Shake(direction, seconds, defaultAmplitude, defaultPeriod)); | |
} | |
public IEnumerator Shake(Vector3 direction, float seconds, float amplitude, float period) | |
{ | |
startPosition = transform.position; | |
direction = direction.normalized; | |
var endTime = Time.time + seconds; | |
var invert = false; | |
while (Time.time < endTime) | |
{ | |
transform.position = startPosition + (invert ? -1 : 1) * direction * amplitude; | |
invert = !invert; | |
yield return new WaitForSeconds(period); | |
} | |
var hack = gameObject.name == "Level Camera"; | |
if (hack) | |
transform.localPosition = new Vector3(0, 0, -10); | |
else | |
transform.position = startPosition; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment