Phase 1: Camera Shake

The time has come to wrap up Phase 1 challenges and this one is a breeze compared to the others. Today I’ll be implementing a camera shake when the player takes damage.

When the player takes damage, provide a subtle camera shake.

Creating the Camera Shake

Since we’re working with the camera, I decided it would be practical to attach the script I’ll be creating on the camera directly. And since we’re creating an effect, I created a new script in my effects folder and named it “CameraShake” and attached it to the camera.

Opening the script I removed the start and update functions and created a new Coroutine. I needed to add two parameters to the IENumerator function. One parameter is the magnitude which is how much the camera will shake and the other is duration which is how long the shake will take. I needed to create a new float in the function to check how much time has elapsed. I then created a while loop and checked if elapsed is less than the duration. Inside the loop, I created two new float values. One for the x position and the other for the y position. Each value has a Random.Range between -1 and 1 and that is how much the screen will shake on each axis.

Then I updated the position of the camera using transform.localPosition and assigning a new vector3 with the values. Lastly, I needed to change the elapsed time by adding it with Time.DeltaTime. Lastly, if the elapsed time is reached we needed to return null and set the camera back to its original position.

Implementing the Camera Shake

Since our player damage is done on the player it would make sense to implement the camera shake there as well. Now we have a lot happening in the player’s damage function I decided it would be best to add the camera shake right at the start to cause the shake even if the player had a shield or not.

All I needed to do is start a new Coroutine and reference it to the CameraShakeRoutine on the Camera. But remember we need to add those parameters to the routine. I set the duration and magnitude to 0.2f for a short and subtle shake that’s visible in the game but isn’t overwhelming to the player.


And just like that, we have a subtle camera shake whenever the player takes damage. It was very easy to implement and it works surprisingly well. And since this challenge is now completed, it also concludes the Phase 1 framework. I’ll be writing one or two more articles before I start with Phase 2: Core Programming since I want to cover additional information I learned like how I implemented an editor only cheat button for testing purposes, but doesn’t get into any builds.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store