Main Content
A Simple Hit-Test
Welcome to Foundation Flash tutorials. In this tutorial you are going to learn an essential part of game development. Hit testing. You will be making something that looks a bit like this:
So let's start by drawing the two shapes that you want to hit test. Draw a circle of one colour and a square of another colour. I made their alpha values 50%, but you don't have to. Convert them to Movie Clips (F8), and call one circle and one square, and give them both instance names of "circle" and "square". You can do that by finding this, highlighted, box when you click on one of them:
You may want to motion tween them as I have done. Now, draw in a dynamic textbox (put in some standard text, click on it and change the drop down in the properties box to "dynamic"), and give it an instance name of "hittext". Time to add the ActionScript.
Click on the square and press F9 to open up its action panel. In it, type the following:
onClipEvent (enterFrame) { if (this.hitTest(this._parent.circle)){ _root.hittext.text = "Ouch!" } else { _root.hittext.text = "" } }
If you test your movie, you should see it working. I'll now explain that code.
onClipEvent (enterFrame) {
This you should already know by now, but just as a reminder, it is the clip event "enterFrame", which carries out all the things in the curly brackets every time you enter the frame. Now, this is the important part:
if (this.hitTest(this._parent.circle)) {
This is an if statement, as you should well know, but inside that, is the hittest function the structure of this function is: MovieClip1.hittest(MovieClip2). You must note however, that this simple hit testing will only check if the square box around the Movie Clip is hitting the square box around another Movie Clip, so it isn't very precise, but works fine in many game situations.So, what this line of code is asking is: "Is this Movie Clip hitting that Movie Clip?", and then if it is, it will do what is inside the curly brackets, which is:
_root.hittext.text = "Ouch!"
In other words, make the hittext textbox's text equal "Ouch!". Then, a simple else statement:
} else { _root.hittext.text = "" } }
So, if not, it will make the text box equal nothing. That is our complete code, so I hope you've learned something, and please join us next time for our next tutorial,
Leon.