Advertisement
gameDevTeacher

Simple 2D ScreenShake

Apr 20th, 2022
770
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.15 KB | None | 0 0
  1. using System.Collections;
  2. using UnityEngine;
  3. using Random = UnityEngine.Random;
  4.  
  5. namespace SimpleCamShake
  6. {
  7.     public class CameraShakeBasic : MonoBehaviour
  8.     {
  9.         private IEnumerator _enumerator;
  10.         public float _duration = 0.1f;
  11.         public float _magnitude = 0.5f;
  12.  
  13.         private void Update()
  14.         {
  15.             if (Input.GetKeyDown(KeyCode.A))
  16.             {
  17.                 _enumerator = Shake(_duration, _magnitude);
  18.                 StartCoroutine(_enumerator);
  19.             }
  20.         }
  21.  
  22.         public IEnumerator Shake(float duration, float magnitude)
  23.         {
  24.             Vector3 originalPos = transform.localPosition;
  25.  
  26.             float elapsedTime = 0f;
  27.  
  28.             while (elapsedTime < duration)
  29.             {
  30.                 float xOffset = Random.Range(-0.5f, 0.5f) * magnitude;
  31.                 float yOffset = Random.Range(-0.5f, 0.5f) * magnitude;
  32.  
  33.                 transform.localPosition = new Vector3(xOffset, yOffset, originalPos.z);
  34.                 elapsedTime += Time.deltaTime;
  35.  
  36.                 yield return null;
  37.             }
  38.  
  39.             transform.localPosition = originalPos;
  40.         }
  41.     }
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement