How can hitTestObject work for many objects?

107 views Asked by At

I have a game where player moves forward over (semi)random tiles. I want a hittest for when the player hits a certain tile.

However when the char hits one of the spawned in floor2's nothing happens.

I think this is because there are multiple 'floor2' movieclips on the stage ?

When i trace the bounds "getBounds" for floor2 the positions it shows keeps changing anyway to Hitest with all of them ?

function handleCollision( e:Event ):void {      
if(char.hitTestObject(floor2)){
trace("hit detected");
}

This is how the player spawns in:

var char:Char = new Char();
char.x = 275;
char.y = 786;
cam.addChild(char);

This is how floor2 spawns in :

if (randomRounded > 10 && randomRounded <= 50 ){
floor2 = new Floor2();
floor2.x = -8.45;
floor2.y = 786 - tileCounter;
cam.addChildAt(floor2, stage.numChildren-1);

Extra : ( RandomRounded is a randomly generated number ), ( there is a 'Var floor2:Floor2;')

please help :(

1

There are 1 answers

2
null On BEST ANSWER

A variable can only ever reference up to one value. So your floor2 variable can only reference one Floor2 object. If you assign a new value, the variable will reference that value.

What you should do is to use an Array, which can hold many objects.

var floors:Array = [];

if (randomRounded > 10 && randomRounded <= 50 ){
    floor2 = new Floor2();
    floor2.x = -8.45;
    floor2.y = 786 - tileCounter;
    cam.addChildAt(floor2, stage.numChildren-1);
    floors.push(floor2); // add the reference to the array, now floor2 can safely be overwritten by a new value without losing the previous one
}

In your function handleCollision you would then iterate over the array to test each individual floor object. Here's a quick untested example of how that could look like:

function handleCollision( e:Event ):void 
{ 
    for (var i:uint = 0; i< floors.length; ++i)
    {     
        if(char.hitTestObject(floors[i]))
        {
            trace("hit detected");
        }
    }
}