Tip of the Day: Simple 2D Camera Shake in Unity

Mohamed Hijazi
Nerd For Tech
Published in
2 min readMar 26, 2021

One of the best ways that increases player immersion in the game is a Camera Shake.

Camera shakes are especially useful for explosions, when player takes damage, or for collectibles.

If you are not using Cinemachine, here is a simple way to do it.

Start by creating a C# script call it CameraShake (or whatever you want) and attach it to your main camera.

//This script will only hold the function that you are going to call when needed from other scripts// Create an IEnumerator that takes two variables
// A variable to control the duration of the shake
// Another variable to control the magnitude of the shake
// Start the method by declaring a new Vector3 originalPos to determine the camera's starting position
//Declare a float for elapsedTime and set it to 0f
//For the shake: best do it in a while loop as long as the elapsedTime is less than the duration of the shake//In the while loop, set two floats, one for the xOffset and one for the yOffset and multiply each by the magnitude (it is good to use a random range for each offset// Set the localPosition of the camera based on these two offsets
// finish the loop by incrementing the elapsedTime with Time.deltaTime
//Finally after the loop is done, set the localPosition to the originalPos and close the IEnumerator method

Use this script to call the shake whenever you need. If you are up to the challenge then try writing the code from the above Pseudocode.

Here is the final result

Camera shakes when destroying the asteroid or when taking damage

One final note, to achieve best results when the main camera sets back to its original position you need to add child the camera in its own parent game object

--

--

Mohamed Hijazi
Nerd For Tech

A knowledge seeking biologist who is following his passion into a full time career in Unity / Game Development. https://www.linkedin.com/in/mohamed-hijazi/