Smart Enemies Dodge Incoming Fire!
Objective: Create a function for basic enemies to detect when the player fire at them and dodge out of the way!
Pilots in a fire fight would never, fly directly into oncoming enemy fire. We are going to give our enemy pilots the same instincts. We want our enemies to be able to look in front of themselves and detect if the player has fired a laser towards them.
A common method to handle this is RaycastHit2D. RaycaseHit2D is used to detect objects that lie along the path of a “ray.” Imagine a laser beam from the front of the enemy and observing which objects are hit by it.
Partnering this with a Linecast we affectively turn this “ray” into a line and can set the location of the line as well as the trajectory with a Layer Mask.
Layer mask is a function we can use to set the Linecast to search for colliders on a certain layer of our game. This means, we don’t need to worry about having a reference with the objects in question, such as the player’s incoming fire. Instead, we can set the players incoming fire on a layer by itself and if the Linecast detects the collider then it will act.
Setting the layers is important, so labeling correctly is equally important.
When the Linecast detects an object, we want the position to change. We want the enemy to move quickly to the side and miss the players shot. Simply adding to the x axis and the enemy is save from harm.
If you want a visual representation of your Linecast then you can use this debug function.
Set the position to the enemy’s position, the trajectory, multiplied by how far you want the line to travel, and I set the color to red so it is easier to see. This will show you the Linecast in the scene view. You may need to turn Gizmos on by clicking on it in the top right of the scene view.
This is all there is to it. Now if your enemy detects incoming fire they will quickly move to the left, to avoid collision. Another popular use for RayCast is creating boundaries in video games. As always, never be afraid to experiment with your code, and I’ll see you in the next tutorial.