It’s been awhile since I’ve posted any new code as part of the code bits, so I’m at it again today. This time you’ll be learning about the hitTest, and its various uses.

The hitTest does pretty much what it’s name suggests. It tests to see if one movieclip is ‘hitting’ another one. A form of it is used in almost every type of game you play. Whether it’s testing to see if a bullet is hitting an enemy, or a character is touching a platform it is a bit of code that can be used for many different ideas.

There are two different kinds of hitTest. First is the basic hitTest. This will only test the bounding boxes of each movieclip. Imagine an invisible rectangle surrounding your movieclip. That is what a basic hitTest uses. It tests to see if the bounding boxes are touching. Now, you can already see what is wrong with this; it only tests the rectangle around your movieClip. It’s not precise enough for most games. But here is an example of it in use:

onEnterFrame = function(){//every frame, run this function
	if(player.hitTest(wall)){//if the player's bounding box touches the wall's bounding box...
		trace("hit");//trace 'hit'

The first line basically says, each frame run what is inside the function. The second line is the part where the hitTest takes place. It checks to see if the player is touching the wall. If the player is touching the wall, then flash is told to trace hit. The brackets end the function.

Now for the shapeflag hitTest. A shapeflag hitTest is a bit more precise than a basic hitTest. Instead of testing bounding boxes, it will check one point on one movieclip against all the points on another movieClip. It’s good for platformers because you just set the point at the players feet and test it against the rest of the platforms. Here’s an example:

onEnterFrame = function() {//every frame run this function
	if(level.hitTest(player._x, player._y, true) ) {//if any part of the level touches the x and y coordinates of the player...
		trace("hit");//traces 'hit'

The first line creates a function that runs every frame. The next line checks to see if any parts of the movieclip level are touching the x and y coordinate of the player. If they are, then trace the word hit. The next two brackets end the function.

That’s it. I know there are better ways to test for collisions, but hitTest is all I’m going to get into at this moment. What methods do you use for collisions?

Related posts:

  1. Code Bits: Trace
  2. Code Bits: Set Interval
  3. Code Bits: Timeline