Another popular strategy to give the player feedback is to shake the camera during explosions or when the player receives damage. Adding this functionality to when our player takes damage with make it easier for the player to subconsciously track their current lives without relying on the UI in the heat of the moment.
Most of the functionality for this system will be done on a new C# script attached to the main camera (or whatever camera you want to use in your project).
Inside this script we only need a single coroutine. This coroutine will be called by the player script when they take damage.
We set two floats; one to track how long the camera will shake (duration), and the force at which the camera shakes (magnitude).
We also store the camera’s original position in a local variable (originalpos), and a new float (elapsed) to limit the duration of the shake.
Next, we set up a while loop for when elapsed is less than duration. We set two more local variables for the x and y values of the camera’s position, make them a random range, and then transform the camera to those new random coordinates.
The time passed it added to elapsed, ending the while loop and then a yield statement breaks us out of the loop until the condition is met again.
Finally, we place the camera back to its original position.
All that is left to do is start this coroutine from the player script when the player receives damage.
Let’s see it in action!