Enemy Explosions when Destroyed — Part 2
In the last article we created the Enemy Explosion VFX and fixed up the Animator Controller.
In this article we’ll finish up the process by triggering the animation state through code when the Enemy is destroyed!
Enemy code
The first thing we’ll do is create a reference to our Animator, and then Initialize it in the Start() function:
Now we’ll go to our OnTriggerEnter2D logic and call our Trigger right before our Enemy is destroyed.
We have to use String references for this, so either Copy and paste the name of your Trigger Parameter, or double check the spelling so it is EXACT.
But this alone will cause a problem:
Because our Enemy code calls the Trigger then immediately after it destroys itself, it doesn’t have time to complete the Animation before being destroyed.
We can do this by delaying our Destroy() function by a float amount of time.
First, we need to determine the amount of time the Animation lasts for… So we can click on the Animation in the Project window, and in the Inspector window it should tell us the exact length of the animation.
Now we can co back to our Enemy Code and delay our Destroy() function by adding in a float value to it’s parameters:
Another funny bug
With our destroy delay fixed, we now can notice another bug:
When our Enemy is destroyed, the explosion continues with the same speed. It looks a little funny to me, so we’ll change that by slowing down the Enemy once it has been hit:
Now it looks and feels better! The Player isn’t constantly dodging explosions now!
And another bug!
You may like this ‘feature’, I however, do not. When our Player destroys an Enemy, they can still be damaged by the explosion.
Yes this makes sense for real life — ouch, fire is hot! — but in the scope of our game, it will make it very difficult for our Player to escape tense situations with multiple enemies coming at once.
So to fix this, we can destroy the collider of the Enemy when hit, so that the VFX is purely visual!
This fixes our problem of being damaged after the Enemy explodes and we can call this bug settled!
And now, A moment of laughter:
So…… This GIF is from a few sections ahead when I fixed this Explosion Collider bug. I had applied some Post-Processing (which we’ll get to soon), and had not realized that it bumped my GIF file size to 132 MB ! Medium’s file size limit is 25MB… So I had to run it through a couple GIF compressors, haha.
Lesson learned to take File Size in to account now. Sorry if some future GIFS look like this. I will hopefully find a way to reduce the File Limit without sacrificing too much quality. Might just have to make them grayscale… Hmmmmmmm……………
Anyways, Enemies explode now! In the next article we’ll be creating an Asteroid that the Player must destroy to Start the Game! To give them a moment to prepare themselves.