Smarter Enemies with RaycastHit2D
I’ve recently made the enemies in the 2D Space Shooter a tad more aggressive.
For one, they will now track the distance between themselves and the player, and if the player gets too close they will turn to face them and attempt to ram into them. I’m using a similar ‘FaceTarget’ method to the one I used with the homing missiles, which make use of a Vector3 offset and the Quaternion.LookRotation method to know where to face.
And secondly, I’m making use of RaycastHit2D so enemies can detect whether a powerup is in front of them, causing them to fire for effect immediately in order to destroy it.
For the Raycast method, I’m using one Vector2 for the position of the enemy firing the ray, another for the direction the ray should head in (down, relative to local space rather than world space), and how far I’d like it to travel (in this case, 10 units or 10f). I’m then checking to see whether this Raycast hits anything and then check to see whether the object it’s hit has a ‘Powerup’ tag before firing a laser at it.
Lastly, in both of these cases I’m using this handy Debug.DrawRay method to draw a line/visualise (in the editor) the direction the enemy is facing as well as the range of the Raycast. I do need to double check whether the Raycast is actually pointing in the same direction, however, as I suspect the raycast is actually pointing down in relation to the object whereas the ray is pointing down in terms of world space. This generally isn’t a problem, as most of the time the enemies are facing down in world space, but it does just mean there’s an opportunity for the debugging ray to be misleading.
// As a quick note: I needed to change the layer of the enemy to ‘IgnoreRaycast’ to prevent it getting hit by its own ray, but hopefully there should be another way around this (as I’m hoping for something else in the game to use raycasting on enemies).