3

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.

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.