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!
Firstly, I’ll create a brand new monobehaviour script called CameraShake. I will place it on the camera we want to shake, in the Unity Hierarchy.
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.
Components of a good “shake”:
What does a good shake effect involve?
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?
For number 1, I’ll use an IEnumerator coroutine to create a limited-duration effect.
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.
Now I need a public function to start this Shake coroutine.
Add some code to test the effect:
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!