Homing missile in Unity
What does every little spaceship need when flying through space? That’s right, homing missiles.
This is how it will work in the end.
First we need to make the prefab for the pickup and then create the homing missile prefab. I have decided to create a powerup that fires 5 missiles at once and they will track an enemy in that is available in the hierarchy.
We now need to think about the behaviour we need from our homing missiles.
We will need a speed to move the missile, a rotation speed so that they can turn and track new enemies, we need a reference to an enemy and to the missile’s rigidbody.
Once the player picks up the homing missile powerup and they press fire, we need to setup the missile in the start method.
I first set the rigidbody reference to the attached component to the missile. I then start a coroutine to give a small delay in starting to find an enemy.
What do we do now that the missile has found an target? We need to move the missile towards the target position. But we need to continually do this as the enemy is always moving. All of this should happen in the FixedUpdate() method as we’re dealing with Unity’s physics.
First we check to see if the missile has found a target, if they have not then it will search again in the hierarchy.
Once the target is found we get the direction that the missile needs to travel with a Vector2 as we’re in a 2D game, we need to cast the target position to a Vector2 as it is a Vector3. We then need to minus the missile position, so now we have a vector that is in the direction of the target.
We then normalise the vector so that it has a magnitude of 1, this makes it easier to times the vector.
Now we need to tell the missile how much it needs to rotate to follow the enemy. We use the Cross product to determine the angle of the direction we need to use.
The cross product returns a vector that is orthogonal to the two original vectors. This tells us in which direction we need to turn towards. For a more thorough walkthrough of the cross product I would recommend Freya Holmer’s video, timestamp is around 2hrs 15 mins.
Continuing on with moving our missile we then need to change the angular velocity of the rigidbody by using our rotationAmount of type float and we minus the float because otherwise the missile will move away from the target. Test it out and see for yourself. We times this by our rotateSpeed and we’re nearly there.
Lastly we need to give the missile rigidbody some velocity. This is similar to the angular velocity above.
For the velocity movement I am firing my missile to the right from the player so that is why I have transform.right. If you’re firing up from the bottom you should use transform.up. We times this by the missile speed and now we have a working homing missile.
That’s it for getting your homing missile working. Come back for more article on game development in Unity.