42:Camera Shake!

Tyler Smallwood
3 min readJun 2, 2021

--

Objective: Every time the player gets hit shake the screen a little bit.

To start off for shaking the camera, we will need a few variables. We need a Vector3 to hold a reference to the position we want the game to stay at. Next is a float for how long the shaking will last, the current shake duration, and how strong the shake will be. Finally we’ll have a bool to see if it’s time to shake the camera.

In the start function we will set the currentShakeDuration to the shakeDuration. As well as assing the originalPos to the current transform.postion.

In the Update function we will need to check to see if it’s time to shake the camera, to do this we’ll see if the bool isShakeCameraTime is true. If it is check to see if the current duration is greater than zero. With the currentShakeDuration greater than zero, we’ll take the current transform.postion and assign it to the originalpos plus a random unit inside a circle multiplied by the shakeStrength and Time.deltaTime. Random.insideUnitCircle returns value within a circle that has a radius of 1. We’ll also subtract the currentShakeduration by Time.deltaTime.

If the the currentShakeDuration is zero or less, we’ll return the transform.position back to the originalPos. We’ll make the isShakeCameraTime back to false and assign the currentShakeDuration back to the shakeDuration.

Now that the camera will have a little shake, we will need a way to assign a true value to the isShakeCameraTime. We’ll do this by creating a public function and inside it we’ll assign the bool to true.

In the Player script, we need a reference to the CameraShake script.

As well as finding the game object that has it attached and check to see if it’s null.

In the Damage function we will call the public function from the CameraShake script.

So now, every time the player receives damage, the shakeCamera will be called and the camera will move around a little bit. On the main camera, that has the script, you can adjust the values as needed. Higher the number the stronger the shake.

--

--

Tyler Smallwood
Tyler Smallwood

Written by Tyler Smallwood

I am passonate on learning to program and use Unity to become a skillful Unity Developer

No responses yet