Here we are at our second appointment with the Pythagorean theorem.
I advise you to read the
first part of this article so to better understand what will come next.
In the first part, we saw how to calculate the distance in between two objects.
Now, we will discover how to detect the collision of two objects using the Pythagorean theorem.
Many of you would surely think 'what's the use of Pythagora to detect the collision when we have the method hitTestObject available''
To detect simple collision, hitTestObject remains a valid method. For more complex collisions and specially when developing flash games, Pythagora is the best way to go.
Let's see the example'
I create a FLA and save it as 'collisione_pitagora.fla' into which I create two MovieClips with the instance names 'ball_0_mc' and 'ball_1_mc'.
I create a Document Class, an AS file saved as 'Collisione.as', implemented the following way:
Code:
package
{
import flash.display.MovieClip;
import flash.events.Event;
public class Collisione extends MovieClip
{
public function Collisione()
{
init();
}
private function init():void
{
stage.frameRate=31;
ball_0_mc.x=0;
ball_1_mc.x=stage.stageWidth;
this.addEventListener(Event.ENTER_FRAME,go);
}
private function go(e:Event):void
{
var x:Number=ball_0_mc.x-ball_1_mc.x;
var y:Number=ball_0_mc.y-ball_1_mc.y;
var distance:Number=Math.sqrt(x*x+y*y);
if(distance<=ball_0_mc.width)
{
this.removeEventListener(Event.ENTER_FRAME,go);
trace('stop');
}
else
{
ball_0_mc.x++;
ball_1_mc.x--;
}
}
}
}
The result:
Let's analyse the code.
Methods
init();
I impost the frame rate
stage.frameRate=31;
I position the MovieClips
ball_0_mc.x=0;
ball_1_mc.x=stage.stageWidth;
I add an interval ENTER_FRAME
this.addEventListener(Event.ENTER_FRAME,go);
go();
I apply the Pythagorean theorem as seen in
this artiche
var x:Number=ball_0_mc.x-ball_1_mc.x;
var y:Number=ball_0_mc.y-ball_1_mc.y;
var distance:Number=Math.sqrt(x*x+y*y);
If the distance is smaller then 'ball_0_mc''s width (as they have a centred registration point)
if(distance<=ball_0_mc.width)
{
I remove the interval and do a trace to advise me of the event
this.removeEventListener(Event.ENTER_FRAME,go);
trace('stop');
}
Otherwise, I move the two MovieClips towards each other
else
{
ball_0_mc.x++;
ball_1_mc.x--;
}
See you next!