Learn to code by making a 2D space shooter game.
Objective: Implement a camera shake when a player takes damage.
In order to do this create an empty game object reset it, rename it camera handler drag the main camera inside a camera handler.

The first step creates a new c script called Camera Shaker and attaches it to the main camera.

In the next step create a new float variable shake time and shake power and serialize it.

Next, create a public method called CameraShake with two float parameters duration and magnitude then assign shake time with duration and shake power with magnitude.

In the next step check if shake time is greater than zero inside late update, then decrease shake time with time .deltaTime.

In the next step, we need to create a float variable of x and y then assign it to random numbers then multiply each to the shake power variable.

In the next step, we need to assign the camera to new positions but we don't want to modify the z position so in z we will use transform.position.z which means leave z position as it is.

Note: we run this inside late update because the damage happens first inside update we need to shake after being hit. If you run this code inside the update the result will be different since the late update is called last.
In the next step, we need to make the camera shake then decrease shaking smoothly until it stops, we do this in 2 steps first is creating a float variable called shakeFadeTime equal to magnitude divided by duration.


Now we go to late update to assign shake fade time to built-in function to smooth it, we use mathf. Towards.

current
towards target
.In the next, we need to shake the camera by rotating a lot bit, we need to create two float variables shakeRotation and rotation multiplier.

Note: if you save the serialize then set the value in code the priority is given to the inspector so it will be zero you need to set rotation multiplier in the inspector.

Go to the camera shake method set shake rotation equal to magnitude times rotation multiplier.

In the next step, we need to rotate the camera at random position time rotation multiplier multiply Time. deltaTime to smooth the shake rotation.

In the next step, we need to gradually decrease shake rotation, we do this by assigning shake rotation to Mathf.MoveTowards.

Now go to the Player script create the Camera shaker variable and cache it to the start method.


In the last step go to take damage method then call camera shake when player loose life.

Let's see the final result.

Thanks for reaching here see you in the next article