Feature: Camera Shake
This article will show how to make a simple camera shake effect when the Player takes damage.
Create a CameraShake script and attach it to the Main Camera.
Next, create an Empty GameObject to hold the camera so that the Main Camera will be at position 0,0,0.
In the CameraShake script, we need three variables, a float for the magnitude the camera will shake, a float for the duration of the shake effect, and a bool to make sure that the shake effect is not already running.
Next is a Coroutine to control the shake with arguments for a duration and magnitude. The first thing it needs to do is set _isShakeRunning to true to tell the script not to rerun the Coroutine till completed. Next, we need two local variables, a Vector3 to hold the starting camera’s local position and a float to hold the time left in the shake effect duration.
Now, for a while loop that will run till timeLeft is below 0. We need three local variables inside the loop, two floats to hold the x-axis and y-axis positions created randomly between -1 and 1 multiplied by the magnitude. A Vector3 to hold the next position the camera will move to that is made of the x and y floats. Next, set the camera’s local position to nextPosition, subtract the time since the last frame from timeLeft, and tell the Coroutine to yield till the next frame. Once the while loop is complete, set the camera’s local position to startPosition and _isShakeRunning to false so the Coroutine will run again when called.
Create a new public method that the Player script will call to shake the camera. Inside, add an if statement that checks if _isShakeRunning is false. If so, start the Shake Coroutine passing in _duration and _magnitude.
In the Player script’s ChangeLives method, add an if statement that checks if the amount is below 0 after the shield code. Inside the if, create a local CameraShake variable to hold the CameraShake component from the Main Camera, null check it, and then call the ShakeCamera method.
With the code added to the Player script, the screen will shake anytime the Player takes damage.