Skip to content

Instantly share code, notes, and snippets.

@Raziel619
Created September 14, 2019 19:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Raziel619/fd5009484137e9cd805ca981c3f7f473 to your computer and use it in GitHub Desktop.
Save Raziel619/fd5009484137e9cd805ca981c3f7f473 to your computer and use it in GitHub Desktop.
Unity sample screenshaker for canvas
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ScreenShaker : MonoBehaviour {
public float shakeAmount = 10f;
private float shakeTime = 0.0f;
private Vector3 initialPosition;
private bool isScreenShaking = false;
//Code adapted from Camera Vibration in Canvas Based Unity Game · Yuno's Wonderland
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if(shakeTime > 0)
{
this.transform.position = Random.insideUnitSphere * shakeAmount + initialPosition;
shakeTime -= Time.deltaTime;
}
else if(isScreenShaking)
{
isScreenShaking = false;
shakeTime = 0.0f;
this.transform.position = initialPosition;
}
}
public void ScreenShakeForTime(float time)
{
initialPosition = this.transform.position;
shakeTime = time;
isScreenShaking = true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment