Core Challenge 9: Create a smart enemy that knows the player is behind them and shoots backward.
This was definitely a challenge but let’s take a look at our current CheckMovementByID() code for a preview of how we solved this conundrum!
So we have our enemy ID of 6, and our enemy code is becoming a lot more modular and readable! So let’s see. We move down, we check to see if the player is behind, we…well..that’s for another article coming soon. ;) We fire our lasers and check to see if we’ve reached the bottom of the screen. We’ve covered almost everything else, the relevant function we want is CheckPlayerBehind…
Grab the players position. Check.
grab our relative position to the player: Check!
By pure luck and googling, Unity has a function to see if an object is behind another, it’s the Vector3 Dot method: The official description is thusly:
Description
Dot Product of two vectors.
The dot product is a float value equal to the magnitudes of the two vectors multiplied together and then multiplied by the cosine of the angle between them.
What all this means exactly, I’m still a bit fuzzy myself, but giving us the formula to know when an object is behind us is ultimately what I’m after. So if Vector3.Dot(going up, and enemy distance from player) if that angle is under 0, that means the player is behind the enemy, but if it’s over 0, it means the player is in front. my code checks from the other direction but it’s the same thing, really.
So I set up a variable called _enemyLaserGoUp, so if the player is in front, it’s false and if the player isn’t, then it’s true.
In our FireLaser() code, our execution gets much easier. If the boolean is true, we merely multiply the speed of the laser by -1, which means it will move the opposite direction of down. :)
To prevent the lasers from coming out of the middle of the ship, I also added an instantiation position to be added to the transform.position Vector3.
And that’s all there is to it!
Tomorrow we’ll make our enemies truly evil and make them shoot our pickups!