Objective: Implement a camera shake effect for a space shooter game with Unity.
In the previous post I implemented a system to limit the ammunition of the player in my space shooter game with Unity. Now it’s time to implement a camera shake effect to display it every time that the player receives damage.
Creating the shake effect
In order to create the shake effect, let’s create a new script and attach it to the main camera:
Then, let’s open the script and create variables to store the values of the new properties that the camera will have to simulate the shake:
By using [SerializeField] we’ll be able to edit the private variables from the inspector to try different values:
Let’s also add new variables to store the original values of the camera to restore them after simulating the shake effect:
Then, let’s create some variables to help in the process:
To avoid memory allocation, we create a WaitForSeconds variable that we’ll define later and use it inside a coroutine to help with the shake effect.
- _newPos, _newRot
To define the Vector3 value of the new position and rotation of the camera.
To multiply the position vector and only invert the X and Y axis.
Now in the Start method, let’s initialize the original values of the camera and the help variables:
Then, let’s create a new coroutine to simulate the shake effect:
First, let’s change the field of view (FOV) of the main camera with the new value, and then, let’s wait for the delay to run the next lines:
Now, let’s change the position and rotation of the camera with the new values, and then, let’s wait for another delay to run the next lines:
Then, let’s change the position and rotation of the camera with the new values inverted to wait for the last delay:
Finally, let’s restore the original values (FOV, position and rotation) of the main camera:
Trigger the shake effect
In order to execute the shake effect let’s open the Player script and create a new variable to store a reference to the CameraShake script component of the main camera:
Then, let’s initialize the variable in the Start method:
Don’t forget to add the respective condition to detect if the script wasn’t found:
Now, in the method that handles the player’s damage, let’s add the call to the camera shake coroutine using the StartCoroutine method:
If we urn the game in Unity, we’ll see that the camera shakes every time that the player receives damage:
And that’s it, we implemented a camera shake effect! :D. I’ll see you in the next post, where I’ll be showing more features added to my space shooter game in Unity.