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.
private Transform cameraTransform;
[SerializeField] private float shakeDuration = 0f;
[SerializeField] private float shakeMagnitude = 0.5f;
private Vector3 initialPosition;
Next, in the Start function you need to get the transform component of the camera. Then set the initial position of the camera.
cameraTransform = GetComponent<Transform>();
if (cameraTransform == null)
Debug.LogError("The camera transform is NULL.");
} 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.
if (shakeDuration > 0)
cameraTransform.localPosition = initialPosition +
(Random.insideUnitSphere * shakeMagnitude); 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.
public void TriggerShake()
shakeDuration = 0.3f;
Next, head over to the Player script so that you can call TriggerShake. First, add a variable for the camera.
private Camera _mainCamera;
Then get the Camera component.
_mainCamera = GameObject.Find("Main Camera").GetComponent<Camera>();
if (_mainCamera == null)
Debug.LogError("The Camera is NULL.");
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!