2D Unity Screen Shake

using UnityEngine;
public class ScreenShakeController : MonoBehaviour
{
// This is a singleton
public static ScreenShakeController _instance;
public float shakeTimeRemaining = 1f;
private float shakePower = 0.5f;
private float shakeFadeTime;
private float shakeRotation;
public float rotationMultiplier = 7.5f;
public bool screenShaking = false;
// Start is called before the first frame update
void Start()
{
// This is a singleton
_instance = this;
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Z)
&& !screenShaking)
{
StartShake(shakeTimeRemaining, shakePower);
}
}
private void LateUpdate()
{
if (shakeTimeRemaining > 0
&& screenShaking)
{
shakeTimeRemaining -= Time.deltaTime;
float xAmount = Random.Range(-1f, 1f) * shakePower;
float yAmount = Random.Range(-1f, 1f) * shakePower;
transform.position += new Vector3(xAmount, yAmount, 0f);
shakePower = Mathf.MoveTowards(shakePower, 0f, (shakeFadeTime * Time.deltaTime));
shakeRotation = Mathf.MoveTowards(shakeRotation, 0f, (shakeFadeTime * rotationMultiplier * Time.deltaTime));
}
else
{
ResetShakeValues();
}
transform.rotation = Quaternion.Euler(0f, 0f, shakeRotation * Random.Range(-1f, 1f));
}
public void StartShake(float length, float power)
{
screenShaking = true;
shakeTimeRemaining = length;
shakePower = power;
shakeFadeTime = power / length;
shakeRotation = power * rotationMultiplier;
}
public void ResetShakeValues()
{
screenShaking = false;
shakeFadeTime = 0;
shakeTimeRemaining = 1f;
shakePower = 0.5f;
}
}

Contact: | Facebook | Twitter | GitHub |

Please Support!

btn_donateCC_LG

One thought on “2D Unity Screen Shake

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s