Search code examples
actionscript-3for-loophittest

as3 hitTestObject with for loop


I am building a pacman style game, and I am looking to shorten my code. The stage contains 92 instances with instance names of food1, food2, etc. When the player(pacman) hits one of the instances Im wanting to call a funcion.

I started writing it out like this... it works but I don't want to duplicate this 92 times!

if( player.hitTestObject(food1) ) {
    updateScore();
}

if( player.hitTestObject(food2) ) {
    updateScore();
}

Now I'm trying something along these lines, but with no success yet.

function collectFood() {
    var i:Number;
    var pGroup:String

    for (i=0; i<92; i++) {
        pGroup= "food" + i;
        if( player.hitTestObject( MovieClip(pGroup) ) ) {
            pCount+= 1;
            MovieClip(pGroup).y=-300;
            updateScore();
        }
    }
}

Thanks for any help!


Solution

  • Look into storing your food in an Array.

    Set up an Array:

    var food:Array = [];
    

    Add your food items into this array (wherever applicable):

    food.push(myFood);
    

    And then you can use for each to run through the items in this Array:

    for each(var i:MovieClip in food)
    {
        // do stuff with i
        // i represents an instance of your food
    
        if(player.hitTestObject(i))
        {
            pCount ++;
            pGroup.y -= 300;
    
            updateScore();
        }
    }
    

    If you have your food on the stage and want to add them all into this Array, just do this:

    for(var i:int = 0; i<92; i++)
    {
        food.push(MovieClip(this["food"] + i));
    }
    

    I strongly suggest that you look into Object-oriented programming (OOP) for ActionScript-3. Using OOP you'll be able to create a class for your Food and encapsulate everything that a piece of Food should do.

    It will also allow you to have much cleaner and readable code, particularly in the above for each loop, which could look like this:

    for each(var i:Food in food)
    {
        // i is an instance of Food
    }
    

    As an aesthetic benefit, using an application like FlashDevelop will provide extremely helpful tooltips based on what you add to your Food class, eg:

    enter image description here