New Feature — Dodger
Objective: Introduce an enemy that dodges the player lasers
In this article, we are going to create the following components:
- Dodge script
- Dodge Detection Area
Create the Dodger enemy
This enemy is very similar to the Fighter that travels down the screen but with the additional behaviour to dodge the laser.
Make a copy of the enemy prefab and rename it to Enemy-Dodger
In Prefab mode, create empty and rename it to Dodge Area.
Add a Box Collider 2D and edit the dimensions of the collider to cover the area in which we want to detect the laser to dodge it.
Remember to tick Is Trigger.
Implement the Dodge Script
At the top let’s define the dodge speed
Since this dodging area is a child, we need to store a reference to the script that handles the movement of the enemy. We use the transform.parent… to go a level up.
We now need to detect the laser in the trigger area. We do it in the following order.
- Check it is a laser
- Check that the laser has been fired from the player
- Check which side we need to dodge to
Attach this script to the DodgeArea object.
In the EnemyBase, add a new public method to change the sideways direction and add a new line to Translate using this value.
The only final component needed is a Ridgebody 2D added to the DodgeArea and set the Body Type to Kinematic. We do this to separate the triggers from the parent and child. If we didn’t then the script containing the OnTriggerEnter2D would fire off and not the one in the Dodge script.
If you enjoyed reading this article give me a Clap, also if you would like to see more, “Follow” me, so you may be notified of future releases. You may also send me a message if you need any further help.