-INTRO-
So, what is a collision?
A collision is to check whether 2 objects are touching.
Flash has a built-in collision detection function called hitTest(). It has some uses, but we are concentrating more here on advanced stuff.
-hitTest()-
Hit Test? Well, to start it has the following form
instance.hitTest(instance)
or
instance.hitTest(pointx, pointy, shapeflag)
The first method tests whether 2 symbols are touching and returns true if they are. There are huge problems with this, though. Say you have 2 rectangles. One named "r1" and one named "r2". On r1 put the following code:
onClipEvent(enterFrame){
_x = _root._xmouse
_y = _root._ymouse
if(hitTest(_root.r2){
trace("xx")
}
This should work fine. When the 2 rectangles collide, it traces xx to the output window.
Now change the shape of the rectangles. Make it like a blobshape or something.
The code won't work as well, because it draws a rectangle around your objects when using this function.
The second way is like so. hitTest(x,y,shapeflag)
Set shapeflag to true and the point to 275, 200
if(hitTest(275,200,true){
trace("xx")
}
If the symbol is touching the point (275,200) it traces "xx" to the output window. The problem is is that this only works with a single point, but leaves out the bounding box of the symbol (the virtual rectangle drawn around it)
So how do we make it better? We code our own functions or use simple tricks.
-TRICKS USING hitTest()-
You can use mutiple points on an object to test against another object.
OR You can hitTest against a symbol inside another symbol that is invisible and shrunk a little.
-ADVANCED HIT TEST-
*Circle vs Circle
Let's see.... To accurately test 2 circles together, all we need to do is find the distance between them. Make 2 circles, 1 named c1 and 1 named c2 Put this code on c1
onClipEvent(enterFrame){
_x = _root._xmouse
_y = _root._ymouse
radius = _width/2
radius2 = _root.c2._width/2
dist = Math.sqrt(Math.pow(_x-_root.c2._x, 2)+Math.pow(_y-_root.c2._y, 2))
if(dist<radius+radius2){
trace("xx")
}
Test your movie. If the circles are hitting, it will trace "xx". The word hitTest is not found in that code once. What is does is finds the distance using the pythagorean therom. d=[radical]deltax[squared]+deltay[squared]
If the distance is less than the sum of the radiuses, the circles are touching.
By using math you can test collision detection against almost any shapes.
For further reading:
Beizer Curve Collision
http://www.gotoandplay.it/_articles/2004/07/collisions.php
http://www.gotoandplay.it/_articles/2004/07/3dBalls.php
http://www.gotoandplay.it/_articles/2004/09/collisions.php
http://www.gotoandplay.it/_articles/2003/09/collisions.php
~a GG tutorial