1

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 :(

null
  • 5,207
  • 1
  • 19
  • 35
Woolff
  • 43
  • 1
  • 1
  • 6

1 Answers1

1

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");
        }
    }
}
null
  • 5,207
  • 1
  • 19
  • 35
  • Thanks so much, is there anyway for me to test the whole array in handleCollision not just say floors[2] but all the that is pushed to it – Woolff Jun 20 '15 at 15:29
  • @Woolff You have to iterate over it, a for loop is one way to do this. Please check my edited answer for an example. – null Jun 20 '15 at 15:43