AS3 HitTest Checks on ActionScript 3.0

This is an example on how one should do a hittest in ActionScript 3.0.

This is an example of plain simple flash mode, where MovieClipA(red) and MovieClipB(blue) – Red being draggable and blue square listens to the a HitTest condition.

Some criteria needed for this task :-

  • Two movieclips – Red and Blue
  • EventListener assigned to Red to have it drag and drop able.
  • EventListener for EnterFrame for Blue to constantly checks for HitTest condition

For those new in EventListener in ActionScript 3.0 here’s a good tutorial for it.

See sample below :-

Download sample source code here.

//Task to accomplish for HitTest
//1. Two movieclips - Red and Blue (Given instance name MovieClipRed and MovieClipBlue
//2. EventListener assigned to Red to have it drag and drop able.
//3. EventListener for EnterFrame for Blue to constantly checks for HitTest condition
 
//Task 1. is done in the stage itself.
//Task 2. Place an Eventlistener on Red have it drag nad drop able.
MovieClipRed.addEventListener(MouseEvent.MOUSE_DOWN,startDragme);
MovieClipRed.addEventListener(MouseEvent.MOUSE_UP,stopDragme);
 
// Below is the trigger function for EventListener Task 2.
function startDragme(event:Event):void{
	MovieClipRed.startDrag(true);
	StatusTxt.text = "Dragging Red";
}
 
function stopDragme(event:Event):void{
	MovieClipRed.stopDrag();
	StatusTxt.text = "Dropping Red";
}
 
MovieClipBlue.addEventListener(Event.ENTER_FRAME,checkHitTest);
 
function checkHitTest(event:Event){
		if(MovieClipRed.hitTestObject(MovieClipBlue))
		{
			StatusTxt.text = "Bingo - Blue has detected Red";
		}
}