Skip to content

Instantly share code, notes, and snippets.

@dxball
Last active August 29, 2015 14:14
Show Gist options
  • Save dxball/6d363d722647ebd2dbc0 to your computer and use it in GitHub Desktop.
Save dxball/6d363d722647ebd2dbc0 to your computer and use it in GitHub Desktop.
Shake Object by given Time, Range & Magnitude Curve.
using UnityEngine;
public class ShakeEffect : MonoBehaviour {
private float m_ShakeTime = 0.0f;
private float m_StartShakeTime = 0.0f;
public Vector3 ShakeRange = new Vector3 (0.2f, 0.05f, 0.1f);
[SerializeField]
private AnimationCurve m_ShakeCurve = new AnimationCurve(new Keyframe(0.0f, 1.0f), new Keyframe(1.0f, 1.0f));
private Vector3 m_OriginalPosition = Vector3.zero;
void Awake() {
m_OrignalPosition = this.transform.position;
this.enabled = false;
}
void Update(){
if (this.enabled == false)
return;
if (Time.timeSinceLevelLoad - m_StartShakeTime > m_ShakeTime) {
this.enabled = false;
this.transform.position = m_OriginalPosition;
} else {
float t = m_ShakeCurve.Evaluate((Time.timeSinceLevelLoad - m_StartShakeTime) / m_ShakeTime);
Vector3 randMagnitude = Vector3.Scale(this.ShakeRange, Random.onUnitSphere) * t;
this.transform.position = m_OriginalPosition + randMagnitude;
}
}
public void Shake(float time) {
this.enabled = true;
m_ShakeTime = time;
m_StartShakeTime = Time.timeSinceLevelLoad;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment