Objective: Create a camera shake effect when the player gets hit.

Adding a camera shake effect is an easy way to add depth and realism to your game. Whenever the player is hit by a laser or collides with the enemy the camera will shake.

To begin we need to parent the main camera into an empty object.

Now we need to create a script for the camera effect and attach it to the main camera.

Inside the effect script we are going to delete both the update and the start method. Next, create a public IEnumerator and I called mine CameraShake with the float variables duration and intensity.

We want to set the original position and a local float variable set to zero.

With those set we can create a while loop. While the elapsed variable is smaller than the duration, we are going to set two float variables to a random number between -1, and 1 multiplied by the intensity variable.

Now we need to set the local position to a new Vector3, using the two float variables above and the original position for the z axis.

We need to take the elapsed variable and add Time delta Time. This gives up a way out of the while loop, and thus, saving our program from crashing.

now end the while loop with a yield return. We want to tie this IEnumerator with the update method, so we will use a yield return null. This mean the yield will return on the next frame that is being drawn.

Now after the while loop, we want to return the local position to the original position.

migrate to the player script and inside the method you use for damage is where we are going to call the camera shake.

I used the values of .15f and .3f, however, feel free to play with these values and set them to how bit or how long you want the camera shake to last. With the code being in the damage method this mean whenever the players taking damage the camera shake will activate, whether they have a shield or not. As always, don’t be afraid to experiment with your code and I’ll see you in the next tutorial.