[AS 3] Simple Hit Test Class Using HitTestObject Method
No comments
There are many levels of detection for testing whether one object is hitting (touching) another object. The most simple method is to use the hitTestObject method of Actionscript. This is a great method for renderings that will fit within a square/rectangular area, as you can see from the image that a circle’s area is defined by the bounding box.
To start I used this Circle.as file for my circle class
package {
import flash.display.Sprite;
public class Circle extends Sprite {
private var radius:Number;
private var color:uint;
private var xcircle:Number;
private var ycircle:Number;
public function Circle(radius:Number=20, color:uint=0x336699, xcircle:Number = 10, ycircle:Number = 20) {
this.x = xcircle;
this.y = ycircle;
this.radius = radius;
this.color = color;
draw();
}
public function draw(){
graphics.beginFill(color);
graphics.drawCircle(0, 0, radius);
graphics.endFill();
}
}
}
… and here is the document class:
package {
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
public class HitTest extends Sprite {
private var circleOne:Circle;
private var circleTwo:Circle;
private var radius:Number;
private var color:uint;
private var xcircle:Number;
private var ycircle:Number;
public function HitTest(){
init()
}
public function init(){
// CIRCLE 1
// draw the first circle and center it on the stage
circleOne = new Circle(30,0x333333,stage.stageWidth/2, stage.stageHeight/2);
// display the circle
addChild(circleOne);
// CIRCLE 2
// draw the second circle and put in the top left corner
circleTwo = new Circle(20,0x123456,20,20);
// display the circle
addChild(circleTwo);
// make it draggable
circleTwo.startDrag(true);
// LISTENERS
// create the listeners
stage.addEventListener(MouseEvent.MOUSE_DOWN, testHit);
}
private function testHit(m:MouseEvent):void
{
if(circleTwo.hitTestObject(circleOne))
trace ("HIT !!!!");
}
}
}
To run the files, all you need to do is drag the one circle and then left click to determine if the two objects are colliding
Monday, January 14th, 2008 at 10:15 am and is filed under Actionscript 3, HitTest Methods. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.