Let’s give the enemy a brain.
Ok, so we have our enemy AI moving in random directions and shields to help protect them. Now it’s time to give them a brain.
Let’s make it so a random enemy will have the will to kamikaze the player.
To do this I need to change the enemy movement code only slightly. I can leave the same movement code that I have orginally and just another function and case to the code.
This is placed inside the enemy script. First I’m going to be using the physics engine provided by Unity and MovePosition that will give the object momentum. To do this, you should always run this code inside of a FixedUpdate, not the normal update.
Ok, to break this down… I add a rigidbody variable named rb and then inside the Start function assign the rigidbody component to it. I also made a Vector2 variable _movement that will be used later.
I’m going to be giving these “special” fighters their own movement using the physics engine so I created a function called MoveEnemy. Inside of this it is just using the rigidbody and the Unity built in function named MovePosition to give the enemy movement. Note that I did slow the enemy by 1/2 to 2. I found that 4 was just way to fast and these are relentless and don’t give up trying to smash the player.
Once I have them moving down the screen I just made another case inside of the already built CalculateMovement function. So when this particular fighter is called it will use a Vector3 variable direction and assign it the player’s position minus the enemy position (this will move it towards the player). We are going to pass this direction into the _movement variable we created earlier which wilkl be given to the MoveEnemy function. The Normalize part just gives it a value between 0 and 1.
Now, this took me a lot longer than the explanation above. A lot of research in fact, videos and reddit posts to put this together. Again, don’t be afraid to go on the hunt for code. You aren’t going to remember it all and there is so much on the internet that will help you!
Let’s see how these kamikaze enemies play. I just put this code into case 0, 2 and 2 as well so all of the enemies would be like this this way you can see how they work.
Again, a lot of different things you can do here. Speed them up and make them more rare or have a play with the code and have a random chance that they will “lose” the player and start moving another direction.
But for me, I like it this way!