Unity2D Camera Shake with Code

Simple Camera Shake

This is the controller I use to shake the camera in Unity2d. It’s very easy to use! First make a C# script called CameraShake.

using System.Collections;
using UnityEngine;

public class CameraShake : MonoBehaviour
{
    public static CameraShake instance;
    Vector3 startPos;

    void Awake()
    {
        instance = this;
    }

    void Start()
    {
        startPos = transform.position;
    }

    IEnumerator Shake()
    {
        for (int i = 0; i < 3; i++)
        {
            transform.position = new Vector3(startPos.x + Random.Range(-0.1f, 0.1f), startPos.y + Random.Range(-0.1f, 0.1f), transform.position.z);
            yield return new WaitForSeconds(0.05f);
        }
        transform.position = startPos;
    }

    public void ShakeMe()
    {
        StartCoroutine(Shake());
    }

}

Add this to your Main Camera and you’re ready to shake! Example:

/* otherfile.cs */

void Explode()
{
    CameraShake.instance.ShakeMe();
}

Code Details

public static CameraShake instance;
Vector3 startPos;

We declare two variables. instance gives us to access the script anywhere in project with the CameraShake.instance syntax. startPos gives us a place to return once the shaking is done.

void Awake()
{
    instance = this;
}

void Start()
{
    startPos = transform.position;
}

Next we define the two variables. instance is defined as this to give the project access to the script. startPos is the start position of the camera.

IEnumerator Shake()
{
    for (int i = 0; i < 3; i++)
    {
        transform.position = new Vector3(startPos.x + Random.Range(-0.1f, 0.1f), startPos.y + Random.Range(-0.1f, 0.1f), transform.position.z);
        yield return new WaitForSeconds(0.05f);
    }
    transform.position = startPos;
}

IEnumerators are used for Coroutines. You can use Coroutines to add delays within blocks of code. We’re going to use one to shake three times.

The for int loop sets the amount of shakes to 3. Inside we are repositioning the camera’s position by giving it a couple of random values. Every 0.05 seconds the camera repositions itself, and after the third it returns to its original position. Change the numerical values to change how things shake.

public void ShakeMe()
{
    StartCoroutine(Shake());
}

This is the function you use to shake the camera. Coroutines must be wrapped in StartCoroutine() so we wrap in in a simple function. From any script you can call CameraShake.instance.Shake() and it will shake!

Photo credit: unsplash.com/@julietfurst