First thing we need to do is create a missile object and then create and attach a script to it; let’s say MissileBehaviour. Adding the following method to this script:
We will also need to add a variable _missleSpeed and set it to say 5. Then adding the following to the Update() method of this script:
Saving the script, jumping back into Unity and pressing play will give:
Awesome, that works, now to have it go towards an enemy. For this we will need to add another variable to the script, such as:
Next we will need to add the following; to the start of the Update() method:
Save the script, jump back into Unity, drag and drop an enemy prefab into the hierarchy. Then drag this enemy into the _closestEnemy field of the MissileBehaviour script. Pressing play will now give:
Fantastic, now we need add a rigidbody and a collider (set as trigger) to the missile. Then setting the missile tag to laser, and pressing play we will get:
What happens if the enemy is destroyed before the missile gets to it; you may ask. As shown below, it will continue on the trajectory it had before the enemy was destroyed.
This is all well and good, however, how do we now have the player fire the missile? In part 2, I shall endeavour to accomplish this.