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

How to Generate Nice Text Formatting in System Terminal With python

List & Download Files from SharePoint Using Python

Stream Data from MSSQL to Anodot using Apache NiFi

CSS FlexBox explained in a different way

Deploying a django application using docker.

Solve N+1 query problem in GraphQL with Dataloaders

Helpful sites to strengthen my coding skills!

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

Adding colliders to a scene

Completing The White Noise Shader

Cinemachine: Look At and Body

Adding lighting to our URP scene