Skip to content

Instantly share code, notes, and snippets.

@bitbutter
Created April 13, 2015 13:37
Show Gist options
  • Save bitbutter/210eb42b004d84cebb4e to your computer and use it in GitHub Desktop.
Save bitbutter/210eb42b004d84cebb4e to your computer and use it in GitHub Desktop.
Modified version of Michael G's PerlinShake
using UnityEngine;
using System.Collections;
public class PerlinShake : MonoBehaviour, IShaker {
public float duration = 0.5f;
public float speed = 1.0f;
public float magnitude = 0.1f;
public bool test = false;
private Vector3 originalPos;
void OnEnable(){
originalPos = transform.localPosition;
}
// -------------------------------------------------------------------------
public void PlayShake() {
if (this!=null){
StopCoroutine("Shake");
StartCoroutine("Shake");
}
}
// -------------------------------------------------------------------------
void Update() {
if (test) {
test = false;
PlayShake();
}
}
// -------------------------------------------------------------------------
IEnumerator Shake() {
float elapsed = 0.0f;
float randomStart = Random.Range(-1000.0f, 1000.0f);
while (elapsed < duration) {
elapsed += Time.deltaTime;
float percentComplete = elapsed / duration;
// We want to reduce the shake from full power to 0 starting half way through
float damper = 1.0f - Mathf.Clamp(2.0f * percentComplete - 1.0f, 0.0f, 1.0f);
// Calculate the noise parameter starting randomly and going as fast as speed allows
float alpha = randomStart + speed * percentComplete;
// map noise to [-1, 1]
float x = Util.Noise.GetNoise(alpha, 0.0f, 0.0f) * 2.0f - 1.0f;
float y = Util.Noise.GetNoise(0.0f, alpha, 0.0f) * 2.0f - 1.0f;
x *= magnitude * damper;
y *= magnitude * damper;
transform.localPosition = new Vector3(x, y, this.originalPos.z);
yield return null;
}
transform.localPosition = originalPos;
}
}
public interface IShaker{
void PlayShake();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment