Crashing into Enemy Ships
Most of the work is done now; we just need to make sure that the enemy ship knows where it crosses paths with the hero ship and then run a test to see whether the two ships hit each other. If they do, we need to make the enemy ship explode.
Double-click the enemy_mc instance to edit it in place. You can see that the ship moves from right to left and eventually off the Stage. There is also a frame labeled crash.
Add a layer to the enemy_mc Timeline and name it actions.
Scrub the Playhead (drag it) to see where the ship begins to cover up the hero ship. This should occur at frame 30.
Add a keyframe to frame 30 of the actions layer and add the following code.
At frame 40 of the actions layer, where the animation ends, add a keyframe and a stop() command.
At frame 55, where the explosion section ends, also add a keyframe and stop() command. Now, if the enemy ship hits the hero ship, it will explode. If not, it will fly offstage and disappear.
Return to Scene 1.
Open the Library (Ctrl/Cmd+L).
Right-click the enemy_mc symbol in the Library and choose Linkage.
In the Linkage section of the Linkage Properties dialog box, check Export for ActionScript and Export in First Frame.
In the Identifier field, enter enemy_mc. In the previous section, we wrote an attachMovie command that looks for this name in the Library to create new enemy ships based off this symbol. See Figure 3 for the settings.
Click OK to close the dialog box.
Finally, delete the enemy ship from the Stage. Now that it's been set to export from the Library, and the newEmemyShip function creates instances of it dynamically, we don't need it. If we left it on the Stage, it would play repeatedly and be very predictable.
Save your work.
Choose Control > Test Movie again to run the game.
if (this.hitTest (_root.hero_mc)) { trace ("You've been hit!"); gotoAndPlay ("crash"); }
This script says that if the enemy ship hits the hero ship, the Playhead needs to go to the crash frame label and play the explosion. It also says to display "You've been hit!" in the Output window. The trace command isn't necessary, but it's a good way for us to test the collision if things don't appear correctly in the published movie for some reason. Check Figure 2 to make sure that everything matches.
Figure 2 The hitTest method is run at frame 30 of the actions layer, where the enemy ship meets the hero ship. So much drama, so little time.
stop();
Figure 3 Linkage properties for enemy_mc.
Now the hero ship moves up and down when you use the arrow keys, new enemy ships are created every half-second, and if an enemy ship hits the hero ship, it explodes and the Output window displays "You've been hit!"
From here, you can add a script to display the score, create levels of difficulty, and do many other things. Your new mastery of collision detection means you can create all kinds of games in Flash, so go have some fun. Happy flashing!