Day 39: Secondary Power UP! Part 1!
Objective: Create a Missile that will find a target and chase after it!
We are wanting to fire a missile that will run straight unless it detects a enemy in a radius. Let’s knock the first section, moving forward!
We will use transform.translate to move the object up in the game world.
Next we will figure out the rotating and moving toward an enemy. We will use a local variable to set the direction by subtracting the missile position from the targets. We will assign the missiles transform.localRotation to a Quaternion.LookRotation. In the LookRotation we’ll add the local variable to rotate towards. To move the missile in that direction, we’ll use transform.translate again with vector3.up. This is use because with the rotation the game objects up direction is now where the object rotates towards.
To subtract the missile from the targets position we need a reference to it. We set a global target variable. We will set the target in the FindEnemy Fucntion.
Now to set the target. I created a function called FindEnemy. Inside FindEnemy, we use Physics2D.OverlapCircle to find any colliders in a certain radius from the game object. When something is found it is saved as a Collider2D variable. We then check to see if it is an enemy we found, if so set that collider to the target global variable and set isEnemyDetected to true. We need this bool to make sure the missile doesn’t detect a different target and try to go after both.
Now to destroy the enemy. In the enemy class we will check for a trigger and see if it’s a missile.
On the Missile script we’ll do the same but we’ll need to spawn the explosion prefab we created earlier.
Now that the logic is done, it’s time to set up the Game object it’s self.
We need the heatseakingmissile script, a collider, and a rigidbody. On the rigidbody component set gravity to zero, on the collider set isTrigger and set the speed and explosion prefab.
That’s it for the missile! Tomorrow we will discuss the setting up of the powerup to activate the heat seeking missile and how to set up a weighted spawn system to spawn this powerup rarely!