More Feedback — Shaking the Camera

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).

New script on the camera.

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).

Coroutine.

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.

Local Variables.

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.

While Loop.

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.

Final line in script.

All that is left to do is start this coroutine from the player script when the player receives damage.

When the player loses a life, shake the camera for half a second, at a magnitude of .4

Let’s see it in action!

Some nice feedback.

--

--

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
Jack Leavey

Jack Leavey

I am a software engineer with years of experience branching into game development, specifically in Unity. Follow along for guides on creating game mechanics!