Skip to main content
Participant
February 1, 2013
Question

how do I check hitTest with 2 objects from same class?

  • February 1, 2013
  • 1 reply
  • 798 views

I have an object (lets call it circle) and I want to check when this circle hits other circles.

I spawned them in through a Main.as using addChild(circle1) then set the location to each one:

var circle1:Circle = new Circle();

circle1.x = 0.0

circle1.y = 0.0

Right now how I have the code working is:

if(circle1.hitTestObject(circle2))

{

     // do something

}

But I have to check each circle to hitTest with every other circle, which takes a long time.

ex:

if(circle1.hitTestObject(circle2))

if(circle1.hitTestObject(circle3))

if(circle1.hitTestObject(circle4))

if(circle1.hitTestObject(circle5))

Is there some way I can have my Circle() class hitTest other Circle() classes?

Or maybe create an array of circles and hitTest those objects against each other?

This topic has been closed for replies.

1 reply

Nabren
Inspiring
February 1, 2013

Your best bet would be to create a createCircle function and insert them into an array at creation:

var circles:Array = new Array();

function createCircle(startX:Number, startY:Number):void

{

     var newCircle:Circle = new Circle();

     newCircle.x = startX;

     newCircle.y = startY;

     circles.push(newCircle);

}

And then make a checkCircles function as follows:

function checkCircles():void

{

     for (var idx:int = circles.length - 1; idx >= 0; idx--)

     {

          for (var idx2:int = idx - 1; idx2 >= 0; idx2--)

          {

               var circle1:Circle = circles[idx];

               var circle2:Circle = circles[idx2];

               if (circle1.hitTestObject(circle2))

               {

                    trace("Circle " + idx + " collided with circle " + idx2 + "!");

               }

          }

     }

}