Day 36 — Improvements: camera shake and health pickup

Connor Fullarton
2 min readApr 20, 2021

Hey and welcome!

Ok it’s time to shake our camera up a little whenever the player gets damaged, currently it doesn’t feel very impactful so let’s liven it up. This will be a pretty short but fun one.

First let’s create a new script called MainCamera and assign it to our camera object. Once that’s done let’s add in the code:

private bool _isCameraShaking = false;public void ShakeCamera()
{
if (_isCameraShaking == false)
{
StartCoroutine(ShakeCameraRoutine());
}
}
IEnumerator ShakeCameraRoutine()
{
_isCameraShaking = true;
for (int i = 0; i < 5; i++)
{
this.transform.Rotate(0, 0, 1.0f);
yield return new WaitForSeconds(0.1f);
this.transform.Rotate(0, 0, -1.0f);
yield return new WaitForSeconds(0.1f);
this.transform.Rotate(0, 0, 0);
}
_isCameraShaking = false;
}

I quite enjoyed how I put together this one. Firstly there’s a _isCameraShaking bool variable that’s there so that we control when the shaking happens and have a means to stop it.

Before we start the coroutine we’re checking if the camera shaking is false as we don’t want the same coroutine firing off twice at the same time. Next in the Coroutine itself I’ve put in a for loop that loops through 5 times giving our screen a shake 5 times.

To simulate the shaking we’re using transform.Rotate and alternating the z value from 1.0f to -1.0f and then setting it back to 0f alternating the shakes for 0.1 seconds otherwise it would change the values too fast to see.

Lastly let’s add a reference to our main camera component in the start method in our Player script with this:

_camera = GameObject.Find("Main Camera").GetComponent<MainCamera>();

Making sure that we also create the global variable of private MainCamera _camera; to store it in. Then we simply call our camera shaking method in our damage script:

_camera.ShakeCamera();

Then the end result should look something like this:

I don’t know about you but I think that works pretty well!

--

--

Connor Fullarton

Hey and welcome! My name is Connor and my goal here is to put out a daily post for a full year about my game development journey.