Adding a camera shake effect
The first thing we need to do is create a camera shake script.
Add the CameraShake script to the MainCamera game object’s components.
We create some variables to hold our starting camera position, how long the shake should last, how much it should shake, and a Boolean to track the state of CameraShake.
In the Start() method we want to get our original camera position so that we can always revert back to it as needed and use it as a baseline for the camera movement.
In Update(), we want to check that the value of _shakeDuration is > 0, and if so move the camera.
To get the CameraShake script to run at all, we need the ShakeCamera() public method to call on.
Here we can pass in our duration and amount values so that outside scripts can customize the camera shake to each situation.
We also set our state variable to true here.
Updating our Player script
We create a method in our player script that will find the MainCamera using its object tag.
This should be default “MainCamera”.
After a null check to make sure we successfully created a reference to it, we call the ShakeCamera() method on our CameraShake script and pass in the necessary values.
Our LoseLife() method is where we add visual damage to the player when appropriate, so this would be a great place to add our ShakeCamera() call.
Towards the bottom of the LoseLife() method, take note that currently there is just a Destroy game object call with no delay.
I was initially worried that the game object would destroy before our Camera shake could complete, but remember, the effect doesn’t take place on the Player script which resides on the Player game object.
It is an event passed onto a script residing on the MainCamera and thus should be totally fine.
That’s it, go crash into something!