Adding a camera shake effect

The first thing we need to do is create a camera shake script.

Add the CameraShake script to the MainCamera game object’s components.

Code it

We create some variables to hold our starting camera position, how long the shake should last, how much it should shake, and a Boolean to track the state of CameraShake.

In the Start() method we want to get our original camera position so that we can always revert back to it as needed and use it as a baseline for the camera movement.

In Update(), we want to check that the value of _shakeDuration is > 0, and if so move the camera.

To get the CameraShake script to run at all, we need the ShakeCamera() public method to call on.
Here we can pass in our duration and amount values so that outside scripts can customize the camera shake to each situation.

We also set our state variable to true here.

Updating our Player script

We create a method in our player script that will find the MainCamera using its object tag.

This should be default “MainCamera”.

After a null check to make sure we successfully created a reference to it, we call the ShakeCamera() method on our CameraShake script and pass in the necessary values.

Our LoseLife() method is where we add visual damage to the player when appropriate, so this would be a great place to add our ShakeCamera() call.

Towards the bottom of the LoseLife() method, take note that currently there is just a Destroy game object call with no delay.

I was initially worried that the game object would destroy before our Camera shake could complete, but remember, the effect doesn’t take place on the Player script which resides on the Player game object.

It is an event passed onto a script residing on the MainCamera and thus should be totally fine.

That’s it, go crash into something!

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Using Git — how to add a repo to track an existing project

How to Measure UI/Page Load Time in Production

Haproxy LoadBalancer On AWS Cloud

On writing opinionated frameworks

FlutterForce — #Week 35

Compose Your Android Navigation with Custom Arguments

Implementing your own operating system — part 6

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
GameDev Dustin

GameDev Dustin

More from Medium

Tessellation in HDRP

Virtual Cameras w/ Cinemachine in Unity 2020 — Part 6

How To Upgrade Your Project to URP in Unity

Retrospective of the 2D Galaxy Shooter