Objective: After a collision with enemy lasers, add some nice Damage VFX in our spaceship.
Requisites: A Gameobject player, 2 gameobjects with animated sprites showing the spaceship damage and laser-player script communication.
The first step is pretty simple, create 2 empty gameobjects inside the player and attach them an Animator component with their respective animations
Now we open our projectile script and make use of the OnTriggerEnter2D() Unity Event
Step by step:
1- We check if we collided with an object with the tag “Player”.
2- We get the player reference finding the GameObject Player and getting the player script component Player
3-Null check, if we succesfully get the player script, we call the Damage function in our player script. We’ll check the implementation later.
4-We destroy the laser projectile.
After saving and going back into Unity, open the Player script and get into the damage function implementation. In this function, when we receive damage we substract a life with _lives — ;. We also call another method called CheckEnginesVisual(). Here is where the magic happens. Let´s get into it.
For this we will need the engines GameObject references:
Both engines references must be dragged to the player in the Unity Editor to work!
Remember: Good practices in programming say that we should always keep every variable private unless the value is going to be accessed or modified by an external script.
If the player gets damage, we activate and deactivate the engines whenever is needed.
And that would be it for our Damage VFX implementation!