actionscript-3for-loopflash-cs6flashdevelopdisplayobject

How to HitTestObject with Multiple Objects of Same Class?


Okay I can't seem to figure this out. I am new to displayObjectContainer and from what I have read I think I might need to access that in order to check for HitTestObject.

So I have a class called mcCar and another class called mcMainScreen which I gave a name of "mainScreen" through my main engine class like so private var mainScreen:mcMainScreen; I am using Flash Develop for all the coding. Now in the class mcMainScreen I add a Movie clip object to it that I just named "bushes" But I add a lot of them to that mcMainScreen class on Flash CS6 just the visuals no code or anything. Now Usually I would just give the bushes an instance name and say:

if (mainScreen.bushes.hitTestObject(car))
{
   trace("HIT");
}

but since there are multiple instaces of "bushes" added on to the stage of my mcMainScreen Movie clip it only traces the hitTest with one of the bushes and not all of them. So I know I need to add them to an array and use a for loop to loop through all the "bushes" but I am having a lot of trouble doing so correctly. Is there a way that I don't have to give them instance names and can just loop through them all for the hitTes?

Any help would be appreciated thank you in advance!


Solution

  • The best way is to add the bushes to a array.

    var bushArr:Array = new Array();
    for(var i=0; i<mainScreen.numChildren; i++){
      var bush = getChildAt(i) as Bush;
      bushArr.push(bush);
    
    }
    this.addEventListener(Event.ENTER_FRAME, onLoop);
    function onLoop(evt:Event){
    
       for(var j=0;j<bushArr.length;J++){
    
          var bush:Bush = bushArr[j] as Bush;
    
          if (bush.hitTestObject(car))
          {
             trace("HIT");
          }
    
       }
    }
    

    The logic is, you need to create the bush and store it in an array. And in a lop you will check each one from the array with the car instance.