Phase II — Progress Report — New Powerup — Homing Missiles
In this article, I will go over the implementation of the Homing missiles.
The functionality of the homing missiles is simple. The missile will lock onto the closest enemy and move towards them in an attempt to collide and cause damage. In reality, the implementation was a little more difficult.
The first step is to find an enemy to approach. The homing missile has a function that creates a list of all enemies in the scene.
This list then compares the distance of each enemy. The enemy with the shortest distance is assigned as the “_closestEnemy”.
The next step was to determine how to approach the target. I considered 2 options. The first option was to calculate the angle of approach and modify the angle of the missile to match this, this used trigonometry but ended up being clunky as the missile always aimed for the forward direction of the enemies.
The second method, which is the method I used, involved adjusting the velocity and angular velocity on the Rigidbody2D. In this method, we use the direction vector (destination — source) in a method called Vector3.cross. This method takes two vectors and returns a third vector which is perpendicular to the input vectors. This vector is the (opposite) angle the missile needs to rotate in order to face the target. Adding a “-“ to reverse this value provides the correct angle. This value is then applied to the angular velocity of the missile's rigid body to apply the rotation over time.
In the movement code the missile checks to see if it has a current target and if so it will charge towards that target. If there is no target the missile will continue moving in its current direction while looking for a new target.
Now to see it in action.
That’s all for now.