Shake, Shake, Shake!
Shaking the camera on impacts
In the last article, we implemented a scaling thruster bar so that the player has feed back on how long their thrusters last before recharging. Today, We’re going to be looking at the last requirement for the first phase of the GameDevHQ 2D Game Development Certification track, adding a camera shake when the player takes damage! The requirement reads as follows:
Tasks:
- When the player takes damage, provide a subtle camera shake.
CameraShake Script
I elected to use code to shake the camera for this requirement, rather than an animation, because I have a better understanding of how to do this programmatically. To start, I added a new C# script called CameraShake that has a method that takes a duration and a magnitude for the camera shake. This method finds the starting position of the camera it’s attached to so that it can return to that position at the end of the shake. It then repeatedly displaces the camera in a random direction limited by the magnitude passed in for the duration of time that is passed in. Finally it returns to the saved starting position.
Add CameraShake Script to Main Camera
Next I needed to attach the new script to the MainCamera. This allows the UIManager to gain access to the script from the instance of the camera in the scene.
UIManager Changes
Next I needed to add private fields for the Camera and the CameraShaker components in the UIManager class and initialize them in the Start method.
I then added the method that would be called on the UIManager to activate the CameraShaker
Adding the call to the Game Manager
Just like other calls I’ve added to the UIManager in the past, I add a new method to the Game Manager so that the method from the UIManager can be called from the GameManager.
Add the camera shake to the damage method on the player
Finally we add the call to the GameManager from the damage method on the Player classes Damage method.
Next Time!
In this Article, we’ve added a camera shake effect whenever the player takes damage. This was the last requirement to be implemented for the first phase of the GameDevHQ 2D Game Development Certification. Next Time, we’ll Start looking at the requirements needed for the second phase of the certification. If you enjoyed this article, or want to come along with me as I progress on my journey, follow me at gamedevchris.medium.com.