View Full Version : hit test for games [Flash][Actionscript]

08-17-2007, 10:02 PM
I test this script with flash mx...

Now, lets get started

MC= MovieClip

What you will learn in this tutorial:

You will learn how to use the "hitTest" action and how to make something happen once the hitTest it true. In this case it will make the dynamic text box named health to -20.

First open a new .FLA file so you can follow with me. Now once the .FLA is done loading make a circle just don't make it really big. Make this into a MC and give it any name you want. Now go down to properties and go to where it says "" and change it to "enemy" (take out the "'s though.) make another circle and put it as a MC. For the instance name for this one name it "man". Put the man on the left side and the enemy on the right side of the stage.

Now for the enemy put these codes in:

onClipEvent (enterFrame) {
if (this.hitTest(_root.man)) {
_root.health -= 20;
if (_root.health== 0) {
The onClipEvent performs an action when a particular "Movie Clip" event occurs. The "if (this.hitTest(_root.man)) {" means that "if" a certian thing will happen to "this" movieclip which this certain thing is a hitTest which tells you if it hits something. "_root." means that the thing the hitTest is going to look for is the "man". "_root." comes in play again... This time it tells the dynamic text box named "health" to go down 5. now the next line under it tells "if" the health reaches 0 it will "gotoAndStop" at frame 2. so it looks like "gotoAndStop(2);" .... Easy huh?

Ok now make a dynamic text box and give it the "var" name of "health". Put it up like it the right top of the stage.

Now double click on the enemy and create a motion tween for frame 1.
Make a keyframe around frame 25-30. Make the enemy pass through the man so the hitTest can do it's thing.

Almost done!
Go to the actions for Frame 1 and put these codes in:


"stop();" stops your movie or game at that frame. "health=100" means to set the dynamic text box named "health" to have the value of 100.

Now go to frame 2 and add a keyframe there and add anything you want to it cause this frame comes in when your health hits 0.

Now if you want to make a button that leads you to frame 1 add these codes to the button:

on (release){
Yay! We are done, test your movie and wait for your enemy to hit your man... Once they collide the health should go down 20.
Once it hits 0 it should stop you at frame 2. Now try out your play button to make sure it works properly. If it does it will bring you at frame 1 and you will have 100 health. I hope this helped!