How to add Camera Shake in Unity

Опубликовано: 23 Март 2026
на канале: The True Duck
2,419
35

Learn how to add camera shake to your next unity project! Not much more is needed than a simple script!

Assets:
Sound Effect: Casino Slots by touchassembly https://freesound.org/people/touchass...
Sound Effect: Car Blinker by dersuperanton https://freesound.org/people/dersuper...
Scene: https://assetstore.unity.com/packages...

Camera Shaker Script:
using System.Collections;
using UnityEngine;
using UnityEngine.InputSystem;

public class CameraShaker : MonoBehaviour
{
[Range(0, 1)]
[SerializeField] private float DefaultRotationStrength = 0.15f;
[SerializeField] private float DefaultPositionStrength = 2f;
[SerializeField] private float DefaultDuration = 0.5f;

private void Update()
{
if (Keyboard.current.spaceKey.isPressed)
{
Shake(DefaultDuration, DefaultPositionStrength, DefaultRotationStrength);
}
}

public void Shake(float duration, float positionOffsetStrength, float rotationOffsetStrength)
{
StopAllCoroutines();
StartCoroutine(CameraShakeCoroutine(duration, positionOffsetStrength, rotationOffsetStrength));
}

private IEnumerator CameraShakeCoroutine(float duration, float positionOffsetStrength, float rotationOffsetStrength)
{
float elapsed = 0f;
float currentMagnitude = 1f;

while (elapsed [[Youtube doesn't want me putting a less than symbol here]] duration)
{
float x = (Random.value - 0.5f) * currentMagnitude * positionOffsetStrength;
float y = (Random.value - 0.5f) * currentMagnitude * positionOffsetStrength;

float lerpAmount = currentMagnitude * rotationOffsetStrength;
Vector3 lookAtVector = Vector3.Lerp(Vector3.forward, Random.insideUnitCircle, lerpAmount);

transform.localPosition = new Vector3(x, y, 0);
transform.localRotation = Quaternion.LookRotation(lookAtVector);

elapsed += Time.deltaTime;
currentMagnitude = (1 - (elapsed / duration)) * (1 - (elapsed / duration));

yield return null;
}

transform.localPosition = Vector3.zero;
transform.localRotation = Quaternion.identity;
}
}

Timestamps:
0:00 Creating the Script
1:13 Adding the Shake
3:29 Controlling the Shake
4:17 Including Rotation
5:53 Adding Polish
6:52 Final Tips
7:51 Subscribe :)