Adding a Camera Shake

This tutorial will go over how to add a camera shake to help add impact when the player takes damage. I learned how to do this from this blog with just a few changes to get the right amount of shake I was going for.

The first thing you need to do is create a Camera script and attach it to the Main Camera. Then go into the script. First add four variables. One for the Transform of the camera, one to track the duration of the shaking. One for the magnitude that you want to shake the camera. The last is to keep track of the starting position of the camera so that you can always return to it.

Next, in the Start function you need to get the transform component of the camera. Then set the initial position of the camera.

  initialPosition = cameraTransform.localPosition;

Next, in the Update function is where you will track shake duration to see if it should make the camera move. Check to see if the shakeDuration is greater than 0. If it is update the local position to the initialPosition plus Random.insideUnitSphere times the shakeMagnitude. Random.insideUnitSphere will give you a random Vector3 that is of length one. That is why it is called the inside unit sphere. Multiplying that by the shakeMangintude will move the camera slightly off its initialPosition each time creating a shaking motion. Then reduce shakeDuration by Time.deltaTime. If shakeDuration is less than or equal to 0 set the camera position back to the initialPosition.

    shakeDuration -= Time.deltaTime;
shakeDuration = 0f;
cameraTransform.localPosition = initialPosition;

The last part in the camera script is to add TriggerShake function that can be called when the player is damaged. This function will set the shakeDuration to start the shaking.

Next, head over to the Player script so that you can call TriggerShake. First, add a variable for the camera.

Then get the Camera component.

The last step is in the Damage function to call the Trigger Shake function right after you reduce the number of lives.

That is it! Now the camera will shake when you take damage.

Now it is up to you to fine tune your shake for what you want. Use the shakeMagnitude and shake duration variables to adjust how you want your shake to look and feel.

Good Luck Adventurer!




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