Missile Launch!- Game Dev Series 51
Objective: Create homing missile.
So far, all the enemies seem would chase after us. It is time to send something to chase them back!
In this article we will create a homing missile that would chase any enemy shows up in scene.
First we need to create a new gameobject as our missile. With every components needed and create a new script.
In the script, first we need to assign 2 variables. One is an array gameobject to store all the enemies in scene; the other is the chosen enemy.
Then in Start(), we need to search the enemy with tag, and locate their position in a new method.
With this, we will get the nearest enemy gameobject. Then we can make our missile chasing after it.
In Update(), we will set the nearest enemy as target and move toward to it. Which is the same thing that enemies did to us.
Chasing them is not enough, we still need to rotate to them. We will need to calculate angle in this part.
In these lines, first we get the Vector3 direction by using the target position to subtract our position. Then we get the angle from y-axis and x-axis of the direction.
In here we use Mathf.Rad2Deg to change it from radian to degree, which is what we need to use in rotation.
Then we can give the value to our rotation. With Quaternion.Euler, we rotate Vector3.forward(z-axis) multiply the angle value.
However, this would make the side of our missile as front. We need to add an offset to adjust the heading direction.
With this offset, our missile should face the enemy.
Player script function
Back to Player, we need to add the function to shoot these missile. With this special weapon, I will use “F” key as launch key.
Create the variables for gameobject and missile counts. Then use them in Update().
That should be all the basic function of our missile. After created the collide method, spawn routine and powerup pickups, it would all be done!