Creating Enemy Explosions

Ernesto Rocha
3 min readJun 24, 2021

Let’s look at adding some visual effects (VFX) to our game, starting with an explosion that triggers when our enemies are destroyed.

To do so, we are going to want to trigger an animation on the enemy's death.

Like our previous animations, we can simply create a new animation for our enemy, then drag and drop all the sprites. But, if we were to run our game now, the enemy would loop through explosions, we only want this to occur when the enemy is destroyed.

If we go into our Animator window, we will see that our Entry state automatically goes into the new state we just created. Instead, let’s add an Empty state to be our default Enemy animation, so we just have a static enemy sprite. From here, rename our Explosion state appropriately, and we want our transitions to look like the following.

Again, this will still automatically cycle through. So we want to add a parameter to our transition. If we add a Trigger and call it OnEnemyDeath, we can call it from our scripts. Then on our transition arrow, we can select the condition OnEnemyDeath. Now our explosion animation has to be triggered for it to work.

In our enemy script, we want to create a variable to store our Animator component. We can use our GetComponent function and remember to null check.

Now in our OnTriggerEnter2D method, we can set our animator trigger when the enemy hits both the Player and the Laser. This is done using.SetTrigger(“OnEnemyDeath”)

If we run our game, our Enemy still just disappears. This is because we are destroying the game object straight away, thus also destroying the animator.

To fix this, we can create a variable to store the length of the animation and delay our Destroy function by the correct amount of time. After setting our animator trigger we can use it.GetCurrentAnimatorStateInfo(0).length

One thing to also note is that we are disabling the collider once the explosion sequence starts. This is so our player can’t continue to take damage while the enemy is exploding. I did experiment with allowing some time for splash damage from the explosion, but couldn’t get it to feel right. I decided that the fundamental mechanic should just be a simple arcade-style shoot and destroy, with the explosion only being for visual effect.

You may also remember that our enemies respawn at the top of the screen when they leave the bottom bounds. With our enemy not being destroyed until the animation is complete, sometimes the tail end of our explosion animation appears up the top which looks a little absurd. To fix this, we can alter our movement method.

We can check if the explosion animation is currently active, and if so, when it goes below our screen bounds, Destroy the enemy. Else we respawn as normal.

--

--