Flash & AS3 Dynamic hit tests

flash as3 dynamic hit test

I stumbled on to a problem that took me a while to find a simple answer so I thought I’d write it up here.

Basically, let’s assume you have 10 items in your Flash file and you want to detect when your cursor or any other object touches, overlaps or hits them. You could get around this by doing an IF statement for each case something like:

if (myMovieClip.hitTestObject(myTargetMovieClip)) {
  // do something
} else if (myMovieClip.hitTestObject(myTargetMovieClipTwo)) {
  // do something
}

Of course you could also write this all in a switch statement but that still leaves you with some pretty lengthy code. So instead we can use a loop to do all this work for us.

This works by getting every child element of a parent container such as Stage, root, or another movieclip with the syntax such as:

_root.myMovieclip
parentMovieclip.ChildMovieclip

I would recommend that for everything you want to loop through you put them inside a movieclip and to get round some later issues I’d also put that inside another container so:

containerMovieClip.parentMovieclip.ChildMovieclip

So now we can access all your movieclips inside of one, there are a few properties that are useful to know based upon this

.numChildren

As it may suggest this will return the number of movieclips that are inside the one that you call this against e.g.

var howManyChildren:int  = containerMovieClip.parentMovieclip.numChildren;

This gives you the number of items your loop will need to go through, to get a specific child item you can then call it via the index number e.g.

containerMovieClip.parentMovieclip.getChildAt(INDEX)

And once you have an that, you can then retrieve the name or even the frames of that movieclip:

var name:String = containerMovieClip.parentMovieclip.getChildAt(INDEX).name
containerMovieClip.parentMovieclip.getChildAt(INDEX).nextFrame;

So putting that all together you can then end up with:

var i:int = 0; //stores the count
for(i; i < containerMovieClip.parentMovieclip.numChildren; ++i){
  if(myMovieClip.hitTestObject(containerMovieClip.parentMovieclip.getChildAt(i))){
    containerMovieClip.parentMovieclip.getChildAt(i).nextFrame();
    if(containerMovieClip.parentMovieclip.getChildAt(i).name == "myMovieClipName") {
      //Do something for an individual movieclip
    }
  }
}

And in a few lines of code you can then automatically detect whatever it is that your cursor etc… has hit. For a few items that’s not going to have a big impact but what if I wanted to loop through hundreds of items in a game for example, do I really want to write hundreds of IF statements, when this loop will take care of it all for me? This loop gets even more powerful when you add in something like Greensocks tween libraries so you could randomly animate every clip in that for loop.

Be the first to leave a comment. Don’t be shy.

You must be logged in to post a comment.