# Hit the Target With a Deadly Homing Missile

Difficulty:IntermediateLength:MediumLanguages:
This post is part of a series called You Do The Math.
Gravity in Action
Circular Motion in AS3: Make One Moving Object Orbit Another

This tutorial will guide you through adding deadly accurate homing missiles to the arsenal of your next game.

## Final Result Preview

Let's take a look at the final result we will be working towards:

## Step 1: Set up the FLA Document

Create a new Flash document set for ActionScript 3.0. I'll be using the dimensions of 600x400, and a frame rate of 30 FPS. Save the file with a name of your choice.

## Step 2: Create a Document Class

Besides the FLA, we also need to create a document class. Create a new Actionscript file, and add this code:

Save this file in the same directory as our FLA. Name it Main.as.

## Step 3: Link the Main Class with the FLA

In order to compile the code from the Main class, we need to link it with the FLA. On the Properties panel of the FLA, next to Class, enter the name of the document class, in this case, Main.

Then, save the changes on the FLA.

## Step 4: Draw a Missile

We need a missile graphic to be displayed when shooting. You may import a bitmap or draw a shape right there on Flash. I'll be using a tiny shape on this example.

What's important here is that you have to make the missile point straight to the right, since that's the origin point for the rotation. So 0° means pointing straight to the right, -90° means upwards, 90° means downwards, and 180° points to the left. Later on we'll need to rotate the missile according to its direction.

## Step 5: Create a MovieClip for the Missile

Once you have the missile graphic, select it and press F8 to create a Movie Clip. Name it "Missile", make sure the the Registration Point is at the center, and tick the "Export for ActionScript" checkbox.

You'll end up with a Missile MovieClip in the Library.

If you have a Missile instance on the Stage, delete it. We'll be adding the Missile MovieClip by code.

## Step 6: Aim

The first thing a homing missile needs to know is where the target is located. We're going to set the rotation of the missile according to the position of the mouse cursor first. Let's work with the enterFrame Event for a constant rotation update.

Add a Missile instance to the stage, I'm placing it at the center (300, 200). Then calculate the distance from the missile to the mouse cursor (I'm storing it in variables targetX and targetY). Finally, the missile's angle will be the arc tangent of both points (targetX, targetY). The result you'll get will be in radians, but the rotation works in degrees, so you'll need to do the conversion by multiplying by 180/Pi. (To see why, check this article.)

(Not sure what `Math.atan2()` is for? Check out this article on trigonometry.

If you Publish (Ctrl + Enter) the document at this point, you should be getting something like this:

Move your mouse near the missile to see it rotate.

## Step 7: Seek

We got the rotation, now we need the movement. The missile has to seek the target, no matter whether it's a steady or a moving target. What we'll do is calculate the movement according to the current rotation of the missile. Let's set a value for the speed, and make the missile chase after the mouse cursor.

We'll include a couple of new variables to calculate the velocity (vx, vy). When the missile is pointing to the right, its angle is lower than 90° and higher than -90°, so it's always lower than the absolute value of 90°. When it's pointing to the left, its angle has an absolute value higher than 90°. This will determine vx in accordance to speed, then vy will be the difference of speed and vx.

You'll get a missile chasing your cursor.

You can use a different speed if you want.

## Step 8: Create a Missile Launcher

Missiles don't come out of thin air, they are shot out of missile launchers. Let's make a MovieClip representing a cannon (I'll use a simple rectangle), and name it Cannon. I'm going to add a Cannon instance by code, so I'm going to keep the stage empty.

## Step 9: Shoot

Now, instead of adding a missile, I'm just going to add a cannon, and a missile will be added at the cannon's position when I click on the stage. We'll add a Boolean to check if the missile has been shot, and also a new function for shooting after the click.

This is what you'll get:

This doesn't look nice. We have to either make the cannon rotate as well, or force the missile to go upwards right after being shot. Since option #1 is the easiest approach, we'll take option #2.

## Step 10: Less Precision for Better Looks

If the cannon is vertical, we would expect the missile to launch upwards and then get on track towards its target. The approach I'll use to achieve this is to give the missile a starting angle of -90° (pointing upwards), and smoothly rotate to get on track to the mouse cursor. We'll add an ease variable to determine the smoothness or sharpness of the rotation. Then we'll create another variable to keep track of the actual rotation that points straight to the target, while the missile's rotation will change according to the ease we set (ease = 1 will behave just like before, anything higher will make a smoother turn).

Since half of the rotation values are negative, in some cases we'll need to calculate them against 360 to get the actual difference between the target angle and the missile's rotation.

Check it out:

Notice what happens when you move your mouse out of the SWF, and how this is different from the previous example.

## Step 11: Missile Hits, Missile Explodes

Besides the Missile Movie Clip, we need an explosion animation. In my case, I'll make a separate MovieClip with a simple tween of a circle that expands. I'm exporting it as Explosion. Press O to select the Oval Tool, and hold Shift while drawing the oval to get a circle.

For a nicer visual effect, I'll put the circle inside another Movie Clip of its own, and give it a Bevel filter to get a darker color at the bottom and a lighter color at the top. Next, I'll go to frame 10 and press F6 to create a Keyframe, then right-click between frame 1 and 10 and create a Classic Tween. Back on frame 10, press Q to select the Free Transform Tool and enlarge the circle.

Then, create another Classic Tween to frame 20, I'll add a Blur filter effect.

Finally, make it disappear in a last Classic Tween to frame 30 with an Alpha color effect going to 0.

## Step 12: Clean Up the Stage

The explosion animation has to be removed after it finishes, or it will loop indefinitely. Add a new layer and press F6 on the last frame, then press F9 to open the Actions panel, and add this code:

This will make the Explosion instance remove itself after the animation is done.

## Step 13: Explode

Now when the missile meets the cursor, we'll replace it with an Explosion instance. We just need to add a new conditional in the `playGame()` function.

Take a look:

## Step 14: Something Else to Blow Up

Chasing after the mouse cursor was entertaining, but it's pointless in a game; we need to make a target. I'm going to draw a bunch of circles to form a Target Movie Clip.

## Step 15: Shoot the Target

Now we'll add a Target instance for the missile to have a more tangible objective. So we'll replace any reference of the mouse cursor for the target's position. Also, we won't be testing for a hit point, but an object.

The `hitTestObject()` method actually only checks for an overlap between the bounding boxes of the two objects (i.e., the blue boxes that appear when you click an instance of the object in the stage), so watch out for that; it's not pixel-perfect collision detection. However, it does the job just fine here.

You may try placing the target at different locations, as well as the cannon.

## Step 16: Moving Target

We already saw that the missile will chase a moving target, such as the mouse cursor, so now let's make the Target instance move a little.

This isn't realistic physics, I'm just going to make the target bounce vertically. I'll pick a reference point as the ground level, and add a gravity value to affect the target. And to make it more dynamic, I'll increase the missile speed to 15.

If you Publish this now, you should be getting a moving target.

## Conclusion

Whether you want an accurate homing missile, or you'd prefer a smooth animation, you can get both results based on this example. Now you've got a new weapon to add in your arsenal, maybe you could try making a Worms-like game, or even use the algorithm on something other than a missile, like some weird mosquito that follows your character.

I hope you've found this tutorial useful. Thanks for reading!