Making the camera shake in Unity!

A good way to indicate sudden movement, a strong or subtle camera shake is a nice little effect to add to a game.

Today’s Objective: Create a simple camera shake effect to my space shooter game, to indicate sudden motion or damage.

Let’s get started!

Since this is a command we will want to access from multiple places, I’ll make it a singleton by adding a “public static CameraShake” variable called “i” (short for “instance”).

I’ll also add a boolean to indicate if the camera is currently shaking, with a public getter.

Singleton and active boolean

Components of a good “shake”:

1. A continuous (and often seemingly chaotic) changing of position, relative to the camera’s original position.

2. An amount of randomness to position changes.

3. An effect “strength” affecting the maximum distance of position changes from the original position.

4. An effect duration, locking the effect into to a specified time-frame.

How could I code that?

I also want the strength and duration to be changable, so I’ll make them parameters of the coroutine instead of variables of the script.

Now, first things first, I’ll set “_isShaking” to true as soon as shaking begins, and false at the very end. I’ll also cache the current camera position before doing any modifications. Finally, create a local duration timer variable and set to zero.

Now I’ll make a while loop for the shaking effect.

Through testing, I decided that a gap of 0.07 seconds between position changes was good

Now I need a public function to start this Shake coroutine.

I pass in the duration and offset limit parameters here

Add some code to test the effect:

DELETE THIS AFTER TESTING

Apart from some parameter tweaking, and calling “CameraShake.StartShaking([d], Vector2([x],[y]);” whenever we want to start the effect, this is pretty much done!