This page require Adobe Flash 9.0 (or higher) plug in.

AS 3 : 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
//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";
		}
}

Other Cool Related Stuff

2 Comments so far »

  1. Liz said

    am August 14 2008 @ 6:55 pm

    Re: Hit Test Tutorial

    How does the code go once the red button is over the blue button so it locks in the exact spot of the blue and you can’t move it anymore?

    Cheers Liz

  2. Mr.GoodStuff said

    am August 14 2008 @ 8:08 pm

    Hiya liz, just if hittest is true; do this assign coordinate of MovieClipRed’s x and y to MovieClipBlue.x and MovieClipBlue.y this will make blue snap perfectly on to the red. Then, MovieClipBlue.removeListener() on the blue clip to stop it from being dragged another :)

Comment RSS · TrackBack URI

Leave a comment

Name: (Required)

eMail: (Required)

Website:

Comment:

CommentLuv Enabled