Homing Missiles for 2D unity

Jason Dixon
3 min readMar 31, 2021

--

Getting something to track and move towards in unity2d can be a bit daunting, so lets break the steps down.

First we need to find what we are targeting, I will be using my space shooter example so we are spawning in waves on enemies, to find the closest one to our homing missile we get all targets with type enemy and put them in a list of game objects, then using a foreach loop we go through each enemy in the list and if their position is closer then the previous one, default the initial variable with a larger number so it gets replaced instantly with the first enemy. Then once we finish the foreach loop we will have the closest enemy to the missile.

Next is the harder part, we are finding the direction between the current position of the homing missile in its rigidbody and the target position we are using Vector2 because we do not want this to be rotating on the z axis. But since this will give us a variable sized vector2 and we need to normalise it so we can get the cross product of it and our direction, we find the cross product so we can get the angle between the missiles current forward and the target to give us a smooth rotation towards the target, the amount rotated can be adjusted afterwards. Unity has a nice function that can normalise a vector in Vector2.normalize(); or using the variable name you have put the direction in like below.

Once we normalize the direction towards our target, using a new variable we store the rotation in a Vector3 where using Vector3.Cross(Direction, transform.up).z we are inputting the direction we want to get towards and our current trajectory and find the cross product of that along the z axis , we want to be rotation along the z axis because any other axis will make it rotate out of our 2D space and not at all what we want.

we then modify the missiles rigidbodys, angular velocity by the rotation amount, this by default will be pretty slow, so you can multiple that by the amount that would seem reasonable to make it track nicely for your game.

However you may find at this point that the cross product will find us an angle between the 2 in the exact opposite direction, good for something getting away from a moving target but not for a homing missile, that has a simple fix. we use the negative of the cross product to get us in the right direction.

Hope that helps you with your tracking missiles.

--

--

No responses yet