Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenating variable names in AS3

I'm working on an AS3 game right now, and have it set up so that the player sprite can collect coins. This is done by rendering the 'coin' movie clip invisible when it detects collision with the player, and incrementing the coin count by one.

Right now, I have the following loop.

if (coin1Collected == false){
  if (player.hitTestObject(level.coin1)){
    level.coin1.visible = false;
    coin1Collected = true;
    coinsCollected++;
    soundChannel = coinSound.play();
    }
}

I don't want to set up one of these for each individual coin movie clip and coin collected boolean, however I haven't been able to find a way to put them all into a for loop. Is there any way to concatenate a variable with an incremental value inside a for loop? Thank in advance and sorry if this is a dumb thing to ask.

like image 929
jdurc Avatar asked Mar 13 '26 05:03

jdurc


1 Answers

I think you are looking for level['coin' + i]. When i = 5, for example, it's equivalent to level.coin5. And to avoid collecting the same coin twice, why not just check for its visibility?

const NUM_COINS = 10;

for (var i:int = 1; i < NUM_COINS; i++) {
    var coin:Sprite = level['coin' + String(i)];

    if (coin.visible && player.hitTestObject(coin)) {
        coin.visible = false;
        coinsCollected++;
        soundChannel = coinSound.play();
    }
}

If you need to store more information about the coin, you can:

  • create an array, where coinX has the information at index X

  • use a MovieClip and set information as an attribute, because MovieClips are dynamic (coin.pickedUp = true)

  • create a Coin class that already has that information as attribute

like image 191
BoppreH Avatar answered Mar 15 '26 07:03

BoppreH



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!