Giving an Enemy the Ability to Find and Shoot Powerups in Front of it-2D Galaxy Shooter in Unity!

Objective: The enemy is now going to shoot powerups that are in front of it, better get them quickly!

Now that we have given the player the ability to attract powerups to themselves like a magnet, it feels a little imbalanced and we need to start giving the enemies some new abilities. This article is going to cover giving the enemy the ability to find powerup targets in it’s front line of vision and shoot at them. Better use your boost to get them! This feature is going to be all configured through code and we are going to dive into physics raycasting! Let’s get into it…

Let’s Start With Some Code to the Powerups Script

This one is a nice simple addition to the existing OnTriggerEnter2D() method and we are going to check whether the tag is equal to “Laser” and if it is, then we are going to instantiate an explosion at the transform position and keep the rotation as is. We are then going to also destroy both the laser and the powerup.

Implementing our RayCast in the Enemy Script

Let’s start with creating some variables that are going to handle the raycast distance, a bool trigger switch for our cooldown timer and a Vector3 offset for our raycast so that it isn’t stuck inside the enemy sprite. Lastly don’t forget to call our new RayCastShot() method in the Update() method so it is always searching for the powerup.

The first line here is going to draw a red line (ray) on the screen in the “Scene” view at the transform.position of the enemy plus an offset which is going to start it a little lower than the enemy so it doesn’t get stuck inside the enemy sprite. The next parameter is going to be the direction and as you can see here I have had to use -transform.up which draws the ray downwards along the Y-axis as my enemies are moving down the screen. I have also added a _rayDistance to this which is going to match the actual raycast.

The next line is going to cast our RayCastHit2D and store the information in our ‘hit’ variable. It is going to shoot the raycast exactly as the Debug.DrawRay as described above. The reason why I have the DrawRay is so I can see the raycast and debug any issues easier.

Now we are going to check for a true hit. The raycast returns a bool value based on whether it has hit a collider (true) if it has.

Next we are going to grab the hit.collider.tag and check to see if it equalsPowerup”.

Last check is to see whether we have fired our lasers already (5 second cooldown), and if we haven’t then we can run our FireLaser() method and start our PowerupShootingCooldownRoutine() coroutine which is shown below:




Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store