Crafting Enemy Explosions!

Matej Marek
4 min readApr 24, 2021

You play a game, see an enemy, you shoot at him… and nothing happens; he just vanishes. It does sound quite frustrating - to fix this disappointing feeling come explosions - let’s bring life to the game with a boom!

We’ve seen how to ‘Animate Sprites in Unity’ - and today, we are going to have a blast with that knowledge!

First, let’s set up an ‘Explosion’ animation on our ‘Enemy’ prefab.

Now that we have created the animation, we have to set up its behavior. First, we need to turn off the looping of the animation. We do this by opening the ‘Animation Clip’ and turning off the ‘Loop Time’ option.

Now we need to open the ‘Animator’ and make a few adjustments to the animation.

  • First up, we created an initial empty state so that our animation wouldn’t start right away.
  • Next, we have created a transition to the Explosion animation state
  • Finally, we have made a Parameter - an ‘OnEnemyDeath’ Trigger.

But this animation would still misbehave, and when we would try to play the game now, the animation would still play out pretty much right away.

For that, we need to create a ‘Condition’ to our newly created Transition. Here we will use the ‘OnEnemyDeath’ Trigger.

While here, I have also turned off the ‘Has Exit Time’ option so that the explosion animation would play right as the enemy is destroyed. And since we are not using any transitions, I have also changed the duration to 0.

Now we need to look at the code part of the animation - let’s open up the ‘Enemy’ script - here; we need to get a reference to the ‘Animator’ component on every Enemy.

Now, we need to call the animation when the enemy gets destroyed. This is done in two places in the ‘OnTriggerEnter2D’ method - when the enemy collides with the player or a laser - the ‘Destroy()’ method is called.

Instead of this, I have created a new method, ‘DestroyEnemy().’

  • First, we set the trigger that starts off the animation
  • Next, I disable the ‘Collider’ so that while the ship is exploding, the player can’t hit it, and the lasers are not being stopped by the explosion either. This is entirely a personal preference, and it felt better this way for me.
  • The speed of the exploding enemy is set to zero so that the explosion does not move in the game.
  • Finally, we call the ‘Destroy()’ method with a 2.5-second delay so that the animation has enough time to play out completely.

One final thing that I have done, which is also a personal preference, is that I have set the animation speed of the explosion to 2.

But that is it for now, thank you for reading and feel free to follow me for more articles - and as always, good luck and see you next time!

--

--