To create a camera shake effect, follow these steps:
- Create an empty game object in the Scene View and name it CameraRig.
- Parent the Main Camera to the CameraRig.
- Select the Main Camera and add an Animator component to it.
- Open the Animation View.
- Create a new Animation Clip and call it CamNormal. The camera should have no motion in this clip. Add keys for both the camera's position and rotation.
- Create another Animation Clip and call it CameraShake. Animate the camera's rotation and position to create a shake effect. The animation should have about 0.5 seconds.
- Open the automatically created Main Camera controller.
- Add a Shake Trigger parameter.
- Create two transitions:
- CamNormal | CameraShake with the condition: Shake Trigger parameter. Has Exit Time should be set to false and Transition Duration set to 0.2 seconds.
- CameraShake| CamNormal with no conditions: Has Exit Time should be set to true and Transition Duration set to 0.2 seconds.
- Write a new script and call it CamShake.cs.
- In this script's Update() function, we check if player pressed the space bar. If so, we trigger the Shake Trigger in our controller:
if (Input.GetKeyDown(KeyCode.Space)) { anim.SetTrigger("Shake"); }
- As always, the anim variable holds the reference to the Animator component and is set in the Start() function with the GetComponent<Animator>() method.
- Assign the script to the Main Camera.
- Play the game and press the space bar to see the effect.