Pergunta

I've decided to create an Android touch screen game. I am a complete and utter beginner and am learning as I go.

My game has a little elephant that moves up when you press and hold on the screen and falls when there is no contact with the screen. The aim is to collect as many peanuts that fly past as possible to gain the highest score. Pretty simple, you'd think so.

So far, I've managed to get to the point where the elephant can collide with a peanut and the peanut disappears.

My issue right now is, I can't create more than one peanut, with the same instance name of "peanut" because only the one will work and the others will not be recognized. I've done a good ole google search and nothing has really given me the right way to go. Could someone give me a clear answer of what to do or where to go from here?

If you need any more info, the code or a picture of what i've got so far to help you understand just let me know :)

  • Samantha
Foi útil?

Solução

Instance name must be unique, and you cannot use instance name to find a set of movie clips. You should instead use an array, and at creating a peanut add it there too using say push(), and at collecting a peanut, splice it out.

In fact, whenever you get a multi-instance class with similar functionality (aka "collect"), use an Array to store references to all of these, so you will always know that ALL of your instances are accessible through that array.

How to work with arrays

A sample code:

var peanuts:Array=new Array();
function addPeanut(x:Number,y:Number):void {
    var peanut:Peanut=new Peanut(); // make a peanut, you do this somewhere already
    peanut.x=x;
    peanut.y=y;
    peanuts.push(peanut); // this is where the array plays its role
    game.addChild(peanut); // let it be displayed. The "game" is whatever container
    // you already have to contain all the peanuts.
}
function removePeanut(i:int):void { 
    // give it index in array, it's better than giving the peanut
    var peanut:Peanut=peanuts[i]; // get array reference of that peanut
    peanuts.splice(i,1); // remove the reference from the array by given index
    game.removeChild(peanut); // and remove the actual peanut from display
}
function checkForPeanuts():void {
    // call this every so often, at least once after all peanuts and player move
    for (var i:int=peanuts.length-1; i>=0; i--) {
        // going through all the peanuts in the array
        var peanut:Peanut=peanuts[i];
        if (player.hitTestObject(peanut)) {
            // of course, get the proper reference of "player"!
            // YAY got one of the peanuts!
            // get some scoring done
            // get special effects, if any
            removePeanut(i); // remove the peanut
        }
    }
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top