Creating a Camera Shake Effect in Unity3D

Pete Thomasberger
3 min readJun 28, 2021

Objective: Create a camera shake effect when the Player GameObejct collides with another GameObject.

Step 1: In Unity, create a C# Script called CameraShake by right-clicking on the Scripts folder in the Project window and attach the script to the Main Camera GameObject in the Hierarchy window.

Step 2: In the CameraShake script, create a private float variable called _shakeAmount and assign a value of 0.2f, which will determine the intensity of the camera shake. Next, create another private float variable called _shakeDuration and assign it a value of 0f. This variable determines the amount of time in seconds that the camera will shake, and its value is what will need to change in order to trigger the camera shake effect. Then, create another private float variable called _decreaseFactor and assign it a value of 1f, which will basically create a cooldown for the shake effect. Lastly, create a private Vector3 variable called _originalPos which will be assigned to the Main Camera’s fixed position.

Step 3: Create a private method called MainCameraShake(). Within the method, assign a new Vector3 to the _originalPos variable with the Main Camera’s fixed position. Create an if statement stating that if the value of the _shakeDuration is greater than 0, the Main Camera’s position will equal the value of the _originalPos variable, plus a random position value within a set radius (Random.insideUnitSphere), times the value of the _shakeAmount variable. Then, have the _shakeDuration variable equal to the _shakeDuration value minus the _decreaseFactor value, multiplied by Time.deltaTime, which will decrement the _shakeDuration value until it reaches 0. Next, create an else statement stating that the _shakeDuration variable is equal to 0f and the Main Camera’s position is equal to the _originalPos variable.

Step 4: Call the MainCameraShake() method within the Update() method.

Step 5: Create a public method called CameraShakeActive() and assign a value of 0.2f to the _shakeDuration variable. Then, save the script.

Step 6: In the Player script, create a private variable of type CameraShake called _mainCamera.

Step 7: Within the Start() method, access and assign the CameraShake script from the Main Camera GameObject to the _mainCamera variable and create a null check.

Step 8: Within the Damage() method, call the CameraShakeActive() method from the CameraShake script just above where the _lives value is decremented.

Save the script, go back into Unity, and when the Player GameObject collides with another GameObject, the Main Camera GameObejct will quickly shake a return to its fixed starting position.

--

--