Last active
June 7, 2024 09:38
-
-
Save koster/4edb60c2b5404b83fd4edf4f02b0d429 to your computer and use it in GitHub Desktop.
Screen shake a la balatro (put this on your camera)
This file contains 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 ScreenShake : MonoBehaviour | |
{ | |
public float screenShakeSetting = 8f; | |
private float shakeAmount; | |
private float originalShakeAmount; | |
private Vector3 originalPosition; | |
private Quaternion originalRotation; | |
void Start() | |
{ | |
originalPosition = transform.position; | |
originalRotation = transform.rotation; | |
CalculateShakeAmount(); | |
} | |
void Update() | |
{ | |
if (Input.GetMouseButtonDown(0)) | |
{ | |
UpdateScreenShakeSetting(screenShakeSetting); | |
} | |
if (shakeAmount > 0) | |
{ | |
float dt = Time.deltaTime; | |
shakeAmount = Mathf.Max(0, shakeAmount - (50 * dt * (shakeAmount > 0.05f ? 1 : 0))); | |
// Apply shake effect | |
float realTime = Time.realtimeSinceStartup; | |
transform.rotation = originalRotation * Quaternion.Euler(0f, 0f, (0.001f * Mathf.Sin(0.3f * realTime) + 0.002f * shakeAmount * Mathf.Sin(39.913f * realTime)) * shakeAmount); | |
transform.position = originalPosition + new Vector3( | |
(shakeAmount) * (0.015f * Mathf.Sin(0.913f * realTime) + 0.01f * shakeAmount * Mathf.Sin(19.913f * realTime)), | |
(shakeAmount) * (0.015f * Mathf.Sin(0.952f * realTime) + 0.01f * shakeAmount * Mathf.Sin(21.913f * realTime)), | |
0); | |
// Reset position and rotation if shakeAmount is too low, to avoid drift from original position/rotation | |
if (shakeAmount <= 0.05f) | |
{ | |
transform.position = originalPosition; | |
transform.rotation = originalRotation; | |
} | |
} | |
} | |
public void UpdateScreenShakeSetting(float newSetting) | |
{ | |
screenShakeSetting = newSetting; | |
CalculateShakeAmount(); | |
} | |
void CalculateShakeAmount() | |
{ | |
originalShakeAmount = screenShakeSetting * 3f; | |
shakeAmount = originalShakeAmount < 0.05f ? 0 : originalShakeAmount; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment