New Feature — Camera Shake
Adding a little juice to the game
Objective: Enhance the realism of the explosion by adding camera shake to the game with the player shoots the asteroid
Create the Camera Shake Script
We have an IEnumerator method called Shake that takes a parameter for how long we want the shake for and a parameter for the intensity.
We save the camera’s current position, reset the elapse variable that stores how long the shaken feature has been running.
Next, we go into a loop while till we have reached the shake duration.
We randomise both the x and y position based on the intensity and set the camera position to the new x and y.
Increase the elapse time but time delta and keep looping.
After we have reached the duration, we set the camera back to its original position.
Now we can call this method using a Start Coroutine from pretty much anywhere. In this case, we are going to add it to when the asteroid explodes.
In the Asteroid script, let's create a reference to the camera shaken script and finds the Camera Shake script component on the Main Camera.
Next, we add the Start Coroutine to the OnTriggerEnter2D method
Now if we were to run the game now and shoot the Asteroid, you will notice that the camera is definitely shaking but it looks like it is snapping to another position. Let’s create an empty game object and make it the anchor of the camera.
Create an empty game object at the camera’s position and drag the Main Camera as a child of it.
You can really notice a difference when you place the camera as a child. That is it! In the next article, we will explore how to introduce different forms of enemy movements.
If you enjoyed reading this article give me a Clap, also if you would like to see more, “Follow” me, so you may be notified of future releases. You may also send me a message if you need any further help.