Phase II: Enemy Avoid Shot
In this article, I’ll cover setting up a new enemy that can dodge a single shot fired from the player.
Objective: Create an enemy type that can avoid the player’s weapon.
Since I’m creating new enemies, I decided to start using some different sprites for the ships. So first, I got myself a nice selection of ship sprites to choose from. For the enemy that can dodge, I’m using the below sprite.
This enemy will inherit from my BaseEnemy class, and the only modification will be its ability to dodge. I added two new variables shown below.
I decided to use a 2D CircleCast to check if the Player’s laser was within range of the enemy. I also did a Debug.DrawLine() call to partially visualize the path in the scene view. Although it doesn’t show the circle itself, it does let me get an idea of the distance.
Then I check if something was hit and if so, I check if it was the Player’s laser and if the enemy’s _canDodge bool is true.
Now for the actual movement, I set the variable _moveDirection to either -2 or 2. I do this by getting a Random.Range(0, 2) which gives me either a 0 or a 1 integer. Then I check, and if the results 0, I set _moveDirection to -2; otherwise, I set it to 2. Then I change the x position of the enemy to the _moveDirection value. Finally, I set the _canDodge bool to false so that the enemy can only dodge once. The code for this is shown below.
The final step was to add the new enemy to the EnemiesToSpawn array in the SpawnManager.
Now our new enemy can dodge a single shot from the Player.
I hope you found this interesting and maybe a little informative. So, until next time I wish you all the best on your coding journey.