Day 51: Smart Enemy is Smarter!

Tyler Smallwood
4 min readJun 11, 2021

--

Objective: Have the Smart enemy attack powerups and destroy them.

To start off we will are going to create a new ammo for the enemy. This ammo has almost the same as our laser but it can only damage the player and power ups. We will create a new game object, I’m calling the powerupDestroyer. On that game object we will need the new PowerUpDestroyer Script, circle collider 2D and rigidbody2d. Let’s set our speed a little faster than our powerup speed.

In our ammo script, we’ll have movement just like our lasers, but in our Laser script we wont check for isFiringBackwards like we did yesterday. We’ll check for that in this script.

We will take the function AssignFiringUpwards our of the laser script and add it in this script. In onTriggerEnter2D we will check for collision with player and powerups.

That’s it for our ammo, we will just need to assign it in our ammo spot on the enemy.

Now in our SmartType script, we need to change the way it fires upwards. Not much change other than no more for loop plus we need to get the function from the PowerupDestroyer script.

Now it’s time to work on the logic for firing at power ups. In our firing function we will need to use ray cast. Raycast is cast a ray from a spot for a distanced specified, to detect any colliders without interfering with it.

Using raycast for 2D and 3D is different. 3D will come up another time when I work on a 3D game. For now it’s all 2D.

To get the raycast to ignore the enemy we will create a empty game object as a child to the enemy and assign it as the origin.

To start messing with raycast you will need to set up a local RaycastHit2D variable and assign Physics2D.Raycast() to it. Inside the raycast fields you will need to specify where the raycast is starting, the directions and how far it will go.

To make it easier to see we will use Debug.DrawRay(), inside DrawRay we need the place it will start, direction, and color if you want it to be different from white. You will noticed I multiplied the Vector2.Down by 2f, this is how you match the distanced specified in the raycast.

We’ll need to check to see if the hit is not equal to null. If it’s not null check to see what it is colliding with and if it’s the powerup, set canFire to 1 to fire faster.

For the collider to make sure it is the powerup, all of the powerups need to be tagged with Powerup.

And that’s all there is to firing at the powerups to destroy them. Thank you for reading!

--

--

Tyler Smallwood
Tyler Smallwood

Written by Tyler Smallwood

I am passonate on learning to program and use Unity to become a skillful Unity Developer

No responses yet