Skip to main content
Known Participant
July 28, 2010
Answered

Need help with an array, pls could somebody help8-)

  • July 28, 2010
  • 2 replies
  • 498 views

The problem I am currently having is that I want to display variable myblock down 10 times and then test it for collison,

I am using the variable I to store the blocks, pls excuse me as I am new to this, If I manally set the variable i to lets say 1 and 2

and then test for collison it works, but when I use I from the for loop it only detects one object from the array, I think that there is something

probably simple missing such as an extra variable, as you can see from the code I am trying to use the ' i ' to replace for instance addChild(blockarray[1]);

I have set it manually to display two blocks in the code below, collison detection works, but when I want to use a loop to display and test the collison

it only picks up one of the blocks, not sure if this is because variable i is set to 0 in the for loop, any help would be greatly appreciated, this is my first post on here as I'm new to Actionscript, ty for reading8-)

var thehero:BlueBlock = new BlueBlock;
thehero.x=20;
thehero.y=20;
addChild(thehero);


var blockarray = new Array()

for(var i:Number=0;i<10; i++)

// this is where I setup my blocks

{

var myblock:BlueBlock = new BlueBlock;
blockarray=myblock;


blockarray.x = Math.random()*500;
blockarray.y = Math.random()*400;
trace(blockarray);
blockarray.push(myblock);
//addChild(blockarray);


}
addChild(blockarray[1]);
addChild(blockarray[2]);

// Check for keyboard events such as the arrow keys been pressed

stage.addEventListener(KeyboardEvent.KEY_DOWN, myKeyDown);
stage.addEventListener(Event.ENTER_FRAME,blockcollision);

function myKeyDown (e:KeyboardEvent){

if (e.keyCode == Keyboard.LEFT){
thehero.x -=5;
}

if (e.keyCode == Keyboard.RIGHT){
thehero.x +=5;
}

if (e.keyCode == Keyboard.UP){
thehero.y -=5;
}

if (e.keyCode == Keyboard.DOWN){
thehero.y +=5;
}
}
function blockcollision(e:Event):void{
if (thehero.hitTestObject(blockarray[1]))
{
trace("Hit");
    
}
if (thehero.hitTestObject(blockarray[2]))
{
trace("Hit");
    
}
}

This topic has been closed for replies.
Correct answer Andrei1-bKoviI

Try this:

function blockcollision(e:Event):void {
     for (var prop:String in blockarray) {
          if (thehero.hitTestObject(blockarray[prop]))
          {
               trace("Hit", blockarray[prop]);
          }
     }
}

2 replies

AdriannaxAuthor
Known Participant
July 28, 2010

Thankyou very much Andrej for your quick response, it worked perfectly, I can now carry on with my code, thanks again

Adriannax

Inspiring
July 28, 2010

Enjoy! :-)

Andrei1-bKoviICorrect answer
Inspiring
July 28, 2010

Try this:

function blockcollision(e:Event):void {
     for (var prop:String in blockarray) {
          if (thehero.hitTestObject(blockarray[prop]))
          {
               trace("Hit", blockarray[prop]);
          }
     }
}