Phase 2: Enemy Avoid Shot
Objective: Allow the enemy a chance to dodge the players laser shot
To do this we start with adding an enemy object to the enemy and call it laser detector. Then create and add a new script called LaserDetector to Laser Detector object. We also need to add a box collider 2d(set as trigger) and a rigidbody 2d but this time because its a child object and we dont want it to trigger the parent enemy collider(This would cause player and other collisions early as all colliders would be seen as one mesh), we set the rigidbody 2d to a kinematic body type. As you will see in the figure below we made the collider just wide enough and long enough as to not make it impossible to hit the enemy(this took a small bit of testing).
Next open the LaserDetector script and create a serialized gameobject called enemy and assign the enemy in the inspector (I’m only using one enemy, the original for the dodge laser option). Create an OnTriggerEnter2D method and check if the other tag is Laser (Laser is only for the player, enemies are tagged with EnemyLaser).
We will be checking which side the laser is coming from based on the enemy center so the enemy will move in the opposite direction. For this we create an enemy and laser x float and assign it to ther transform.position.x. We also create an int for side variable which will be passed to the enemy. We run an if statement to see if the laserX postion is less than the enemyX and based on yes or no set the side intger to -1 or 1. Finally before moving on we get the Enemy script from the Enemy gameobject using get component as we will need this shortly.
Next open the enemy script and create a private bool called onComingLaser and set to false and create an int called onComingSide and set to 0. Create a LaserDodge method and check the onComingSide to translate the enemies postion based on the value.
Now in the CalcMovement method, start we run an if check to see if onComingLaser is true before calling the LaserDodge method. As you can see in the above figure LaserDodge checks the value of onComingSide which we initially set to 0. We create a public LaserSide method that takes a bool for oncoming and an int for side. This will be called from the LaserDetector script and pass through the variables from the OnTriggerEnter2D. If oncoming is true the onComingLaser bool is set to true and the onComingSide is set to the passed side int value or else onComingLaser is set to false and so on.
Finally reopen the LaserDetector script and inside the OnTriggerEnter, we had already got the Enemies Enemy script using get component. Now we can call the LaserSide method and pass though the bool (true in this case) and the side value of -1 or 1.
We then create an OnTriggerExit2D and if the other tag is Laser and call the LaserSide method and pass the bool(false) and side int value of 0.
In the next post, we will look at creating a homing projectile.