Galaxy Shooter: Camera Shake

In this article I will show how I setup my camera shake for when the player gets hit.

I started by adding a empty gameObject to my hierarchy in Unity and naming it “Camera_Holder” I set the Transform to the values of the Main Camera and then childed the Main Camera to it and zeroed out the position for the camera. I also created a new script named CameraShake and attached it to my Main Camera.

In this CameraShake class I created a public coroutine named Shake that takes 2 float parameters , named duration and magnitude.

It’s a 2d game so I only want to modify the x and y axes so I started with making a Vector2 local variable named originalPos for saving the original position of the camera which is the transform.localPosition.

I then set a float variable named elapsed to 0.0f, this will be used to track the amount of time elapsed since the coroutine was called.

I then use a while loop that runs while elapsed is less than the duration passed into this coroutine from wherever it was called, in this case from my Player class.

This while loop moves the camera transform.localPosition to a random spot within a circle of the default size of 1 unit multiplied by whatever the magnitude float passed in was. The larger the magnitude the more chance of the camera moving further resulting in a more jarring hit.

It takes the transform.localPosition and sets it to the originalPos + (Random.insideUnitCircle * magnitude);

(If it was a 3d game you could use Random.insideUnitSphere and work with vector3 instead of vector2)

It also increments the elapsed value with the time passed with…

elapsed += Time.deltaTime;

yield return null; makes it wait a frame before repeating the loop.

When the while loop finishes when elapsed is more than duration then it sets the camera position back to the originalPos.

Now to call it from my player class each time the player takes a hit I simply call it first thing in my Player’s Damage method and pass in the variables that I made in the Player class.

Unity Developer/C# Programmer for VR, 2d,3d Games and other Immersive Interactive Experiences