Player Hit Sound and Invincibility Frames

Blake Zoeckler
3 min readJun 23, 2021

--

Objective: add polish to effects that happen when the player is hit.

First we’d like to play an alarm sound when the player takes damage. We can’t just use the audio source attached to the player, because that might override the player’s laser sounds when he fires. We also can’t use Unity’s built in method AudioSource.PlayClipAtPoint because we want to be able to change the volume and pitch of the sound that is played.

Instead, we’ll create our own version of PlayClipAtPoint instead a static class. This includes additional parameters that controls the volume and pitch. It also automatically places the new AudioSource object right on the camera so it will play at the proper volume. It the object were placed further away, it would be unnaturally quiet.

Now when the player takes damage, we can call this method that will play the sound, as long as that sound object doesn’t already exist in the game.

Player.PlayHurtSound

Next, we’d like to give the player “invincibility frames” when hit. This will prevent the player from taking multiple hits in a row and losing the game almost immediately. We achieve this by removing the player’s collision and cause him to fade briefly when hit. After a short duration, we stop fading the player’s sprite and turn his collision back on.

We’ll call this new coroutine whenever the player takes non-lethal damage to his lives. The player explodes when lives are zero, so there’s no point calling all these additional effects then.

Player.GainLives

One last adjustment is for the camera shake. It would look a little nicer if the camera shaking intensity decreased over time, instead of just suddenly ending. We can add this line to CameraShakeRoutine to better control the intensity as time progresses.

Here’s the end result. It looks and sounds a lot nicer, and is much less punishing for the player as well.

--

--

Blake Zoeckler
Blake Zoeckler

Written by Blake Zoeckler

I’m a passionate and talented software engineer seeking an opportunity in game development.

No responses yet