Free Action Script 3 code: homing missiles

This article is for the beginners and those, who like to save their time with copy/paste programming. Though it is assumed the reader is familiar with at least one programming language, preferably JavaScript or Lua, if not Action Script.

Ok, here we go. I prefer Flex, but the .fla file is available as well. If you like to put this tutorial on your site, be sure to ask first (please use the contact form). I also would like to mention that the provided code is far from optimal, and is written for educational purposes only.

The final result looks as follows:

Download SWF+Flex Project archive

Download SWF+.fla archive

Detailed description of the program:

  1. Sets up the Stage (scale mode, alignment) and scrollRect property, which defines the clipping area.
  2. Adds the launch pad to the bottom of the screen
  3. Adds the moving target
  4. The launch pad adds a missile when clicked. This is done by setting up a MouseEvent listener.

There's a little difference between Flash CS and Flex versions of the program. In the Flex version, the target object is available from the main class through a static variable, which is bad practice. In the Flash version it is passed as a parameter, which in turn is not convenient at all.

When created, missile draws its picture, and sets up a timer. Each timer tick, it does the following:

  1. Looks up target, getting it coordinates.
  2. Calculates the target angle using the Math.atan2 function.
  3. Adjusts X and Y velocities.
  4. Rotates its picture, basing on the same Math.atan2, but with velocities given as parameters.
  5. Adds velocities to X and Y coordinates.
  6. Looks if the target is hit, by comparing the distance to the center of the target with its radius.
  7. If a hit occurs or TTL (time to live) runs out, the projectile blows up with an explosion.

Hi In my opinion the post's

Hi
In my opinion the post's too short.

hey dude great article thank

hey dude
great article thank you!