Sunday, July 27, 2008

[AS3] Basic collision detection

Here is a basic method of collision detection. First lets make 2 squares, make them both movieclips, and give he instance names square1 and square2. Now lets make it so that you can drag them around the stage, to make them overlap. Here is some basic code to do this:
var drag:Boolean = false;
square1.addEventListener(MouseEvent.MOUSE_DOWN, mousedown);
stage.addEventListener(MouseEvent.MOUSE_UP, mouseup);
stage.addEventListener(Event.ENTER_FRAME, enterframe);
function mousedown(e:MouseEvent):void{
drag = true;
}
function mouseup(e:MouseEvent):void{
drag = false;
}
function enterframe(e:Event):void{
if(drag == true){
square1.startDrag();
}
if(drag == false){
square1.stopDrag();
}
}

Now make a text box and make it dynamic and give it the instance name hittest.Now enter this code in the ENTER_FRAME function:
if(square1.hitTestObject(square2)){
hittest.text = "hitTest = true";
}
else{
hittest.text = "hitTest = false";
}

Post any questions.

No comments: