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; | |
| 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 |


Reblogged this on aSpuriousConjoint.
LikeLike