Collision Detection:
What is it?: Collision Detection can be useful in many ways. When an object is touching another object, flash tells you.
Start:
First, draw two circles. one named circle1 and one named circle2. Next, make two dynamic text boxes, and name them messageTEXT1 and messageTEXT2
Let's create a simple example that examines the cursor location and the location of a moving object every frame.
addEventListener(Event.ENTER_FRAME, checkCollision);
The checkCollision function starts by using hitTestPoint looking at the cursor location to whether it hits the circle movie clip on the stage. The first two parameters of the HitTestPoint function are the X andY location point on the stage. The 3rd location is the type of boundary to use. The default value of false, which means only the bounding rectangle of the display object should be taken into account.
Unless the object is square shaped, this wont be good for gaming. Instead, by stting a 3rd parameter to true hittestpoint will use the actual shape of the display object.
We'll put different text into a message field, depending on the results of the hittestpoint:
function checkCollision(event:EVENT) {
//check the cursor location against the object
if (circle.hitTestPoint(mouseX, mouseY, true)) {
messageText1.text = "hitTestPoint: YES";
} else {
messageText1.text = "hitTestPoint; NO";
}
The hittestobject function doesn't have a shape option. It only compares the two bounding boxes of two sprites. But, it can still be useful in some cases.
The following part the code makes a circle2 movie clip follow the cursor, and puts a different message in another text field depending on whether their bounding boxes intersect.
// Move circle 2 with mouse
circle2.x = mouseX;
circle2.y = mouseY;
// test circle2 versus circle1
if (circle2.hittestObject(circle1)) {
messageText2.text = "hitTestObject: YES";
} else {
messageText2.text = "hitTestObject: NO";
}
}
I hope this has helped!
-MSMstudios