Adding Screen Shake in Unity
For today’s article, I’ll be going over how I added screen shake whenever the player ship gets hit. To see the code, please visit: https://github.com/hlimbo/Space-Shooter-Tutorial
The Code
We start the camera shake via coroutine and will only last for up to shakeDuration
seconds. This coroutine runs at the end of every frame periodically until the timeElapsed
variable reaches the shakeDuration
time. At each step, we calculate a random x and y position and use the Mathf.MoveTowards
function to ease out the shake magnitude over time. This allows for a smoother transition to when the camera position resets back to it original position.
For reference, I’ve attached the Camera Shake script onto the Main Camera Game Object with the following fields set:
To apply the shake whenever our player ship receives damage, we need to find the object that has this component attached in the scene using FindObjectOfType<T>
function where this function is responsible for finding the first game object that has the CameraShake
component attached. Since we only have 1 game object in the scene that has this component attached to, using FindObjectOfType<T>
function in the Start()
function of the Player script is a good idea here:
Thanks for reading :)