Phase 2: Smart Enemy
Objective: Allow the enemy to shoot behind them if the player is within range
There are so many ways to achieve this option and a very common one would be using raycasts but I felt I’d follow the coding so far so I went with the option of using distance between transforms and positions along the Axis.
We start by copying the enemy laser prefab and renaming the copy as enemy laser behind and adjusting the positions of the left and right lasers. Open the enemy script and create a serialized game object called laser behind and assign it in the inspector. We are only going to apply this to the original enemy and not the red enemy so assigning only needs to be done on the original enemy prefab. Next create a private bool for isPlayerBehind and set it to false.
Move to the EnemyFire method and duplicate the enemy laser instantiation logic as we will be triggering one of two prefabs dependant on an if statement to check if the enemy behind bool is true or false. We need to edit the instantiation slightly to adjust the tranform positon so the laser shoots from behind the player rather than in front. We also change from Quaternion.identity to Quaternion.Euler and change only changing the Z rotation to 180 to flip so the laser goes up and not down.
Next using the logic we set in a previous post to allow the enemy to change rotation and ram the player, we change a few variations to give us what we need. First we add an if statement to check if the distance between is further than the range we want and set isPlayerBehind to false. This is needed to turn the bool check off after the isPlayerBehind has been triggered and the player leaves range. Next we add an if else to check if the player is within range and the enemies position on the Y-axis is less than the player and set isPlayerBehind to true. We also set the isPlayerBehind to false if the enemy is attempting to ram the player. I added some logic to prevent the enemy shooting while trying to ram the player as I felt this was necessary as the enemy already has a speed boost and the player needs thrusters as it is to get away.
For this I added an isChasing bool set to false by default. When the enemy is attempting to ram, it’s set to true and when the player is out of range it is set to false again. Then I added and is not chasing to the fire logic for the enemy.
One last thing was to open the laser script and edit the EnemyLaser method. originally this was set so that when the laser was out of the screen below a certain point it would destroy itself and and parent components but now we have a laser that shoots up so the logic now needed to have a below OR an above range to destroy itself and its parent components.
In the next post, we will allow the enemy to try and avoid being hit