Skip to content

Instantly share code, notes, and snippets.

@ftvs
Last active May 8, 2023 05:20
Embed
What would you like to do?
Simple camera shake effect for Unity3d, written in C#. Attach to your camera GameObject. To shake the camera, set shakeDuration to the number of seconds it should shake for. It will start shaking if it is enabled.
using UnityEngine;
using System.Collections;
public class CameraShake : MonoBehaviour
{
// Transform of the camera to shake. Grabs the gameObject's transform
// if null.
public Transform camTransform;
// How long the object should shake for.
public float shakeDuration = 0f;
// Amplitude of the shake. A larger value shakes the camera harder.
public float shakeAmount = 0.7f;
public float decreaseFactor = 1.0f;
Vector3 originalPos;
void Awake()
{
if (camTransform == null)
{
camTransform = GetComponent(typeof(Transform)) as Transform;
}
}
void OnEnable()
{
originalPos = camTransform.localPosition;
}
void Update()
{
if (shakeDuration > 0)
{
camTransform.localPosition = originalPos + Random.insideUnitSphere * shakeAmount;
shakeDuration -= Time.deltaTime * decreaseFactor;
}
else
{
shakeDuration = 0f;
camTransform.localPosition = originalPos;
}
}
}
@rivax95
Copy link

rivax95 commented Apr 17, 2019

Thanks !

@stickylabdev
Copy link

doesnot work at all

@krupasknr
Copy link

thanks,.. so simple

@hergaiety
Copy link

Good stuff!

@sauravrao637
Copy link

sauravrao637 commented Jun 6, 2020

Thanks @ixikos. I expanded on your script to calculate a delta time so the shake duration is retained even when the game gets paused (and Time.deltaTime stops).

using UnityEngine;
using System.Collections;

public class CameraShake : MonoBehaviour {
    public static CameraShake instance;

    private Vector3 _originalPos;
    private float _timeAtCurrentFrame;
    private float _timeAtLastFrame;
    private float _fakeDelta;

    void Awake() {
        instance = this;
    }

    void Update() {
        // Calculate a fake delta time, so we can Shake while game is paused.
        _timeAtCurrentFrame = Time.realtimeSinceStartup;
        _fakeDelta = _timeAtCurrentFrame - _timeAtLastFrame;
        _timeAtLastFrame = _timeAtCurrentFrame; 
    }

    public static void Shake (float duration, float amount) {
        instance._originalPos = instance.gameObject.transform.localPosition;
        instance.StopAllCoroutines();
        instance.StartCoroutine(instance.cShake(duration, amount));
    }

    public IEnumerator cShake (float duration, float amount) {
        float endTime = Time.time + duration;

        while (duration > 0) {
            transform.localPosition = _originalPos + Random.insideUnitSphere * amount;

            duration -= _fakeDelta;

            yield return null;
        }

        transform.localPosition = _originalPos;
    }
}

And of course, call it from anywhere by
CameraShake.Shake(0.25f, 4f);

@sauravrao637
Copy link

Thanks :)

@Ultroman
Copy link

Ultroman commented Feb 17, 2021

Thanks @ixikos. I expanded on your script to calculate a delta time so the shake duration is retained even when the game gets paused (and Time.deltaTime stops).

Couldn't you just have replaced Time.deltaTime with Time.unscaledDeltaTime and had the same functionality?

@krlosrokr
Copy link

Thanks man!

@stewheart123
Copy link

really freaking cool! modified it to run whenever an in-game explosion happens. Added tonnes of feeling to my project!

@Radall
Copy link

Radall commented Jan 12, 2022

Thank you! I put your script in a small Coroutine. Makes my prototypes instantly more fun!

    // used fields
    private Camera mainCamera;
    [SerializeField] private float cameraShakeDuration = 0.5f;
    [SerializeField] private float cameraShakeDecreaseFactor = 1f;
    [SerializeField] private float cameraShakeAmount = 1f;
    // coroutine
    IEnumerator ShakeCamera()
    {
        var originalPos = mainCamera.transform.localPosition;
        var duration = cameraShakeDuration;
        while(duration > 0)
        {
            mainCamera.transform.localPosition = originalPos + Random.insideUnitSphere * cameraShakeAmount;
            duration -= Time.deltaTime * cameraShakeDecreaseFactor;
            yield return null;
        }
        mainCamera.transform.localPosition = originalPos;
    }

@XaviSmith
Copy link

XaviSmith commented Jan 5, 2023

Nice script!

For anyone that wants it I made a version that allows you to skip frames to control how jerky the camera shake is, works on any gameObject, and lets you choose whether or not to run it whenever the script is enabled.

public class ObjectShaker : MonoBehaviour {

bool startOnEnable = true;
float shakeDuration = 1f;
float framesToSkip = 0f; //How many frames to we skip in order to slow down the jerkiness of the animation
public float shakeAmount = 1f;

void OnEnable()
{
    if(startOnEnable)
    {
        Shake();
    }
}

//Parameters are optional. Defaults to object variables.
public void Shake(float _duration = -1f, float _skip = -1f, float _amount = -1f)
{
    if(_duration < 0)
    {
        _duration = shakeDuration;
    }

    if(_skip < 0)
    {
        _skip = framesToSkip;
    }

    if(_amount < 0)
    {
        _amount = shakeAmount;
    }

    StartCoroutine(ShakeCoroutine(_duration, _skip, _amount));
}



IEnumerator ShakeCoroutine(float _duration, float _framesToSkip, float _amount)
{
  //For if you need special logic for Main Cameras (e.g. you have a script that follows the player around that you need to disable temporarily)
    if(gameObject.tag == "MainCamera")
    {
        //Disable here
    }

    Vector3 originalPos = transform.position;

    float currFramesSkipped = 0f;
    bool locked = true;

    while (_duration > 0)
    {
        if(currFramesSkipped <= _framesToSkip)
        {
            locked = true;
            currFramesSkipped += 1;
        } else
        {
            locked = false;
            currFramesSkipped = 0f;
        }

        if(!locked)
        {
            transform.position = originalPos + Random.insideUnitSphere * _amount;
        }
        
        _duration -= Time.deltaTime;
        yield return null;
    }

    //reenable your camera
    if (gameObject.tag == "MainCamera")
    {
        //reenable camera logic here
    }
    transform.position = originalPos;
}

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment