Search code examples
actionscript-3flash-cs5tile

push objects that equal true, into an array


I have an enemy hitting a bunch of tiles, and through a loop, I check all the tiles if the enemy is hitting them. I trace them and some will tell me if it's true or false. I want to be able to get the enemy to randomly choose from those that are true, and go on those tiles. It traces all the tiles that are in contact with the enemy, problem is, I'm not sure how I can get those tiles that are registering as true, into its own array, then have the enemy move randomly into those tiles.

 for (var j:int = 0; j < tileset.length; j++){
     trace(tileset[j].currentFrameLabel, tileset[j].hitTestObject(enemy));
     if (tileset[j].hitTestObject(enemy) && !tileset[j].hitTestObject(player)){
                 options.push(Boolean(true));
            }

EDIT: here's my timer function, where every 5 second, I want the enemy to move to an available tile. Although you can't see tileset, it is an array that is equal to the movieclip that is a tile, which is in a for loop itself. So basically, tileset is 49 movie clips of tile. I have those available tiles pushed into another array which is options. Then I make a var called enemyPick which would be the counter. That's how far I am.

function timerenemy (event:TimerEvent) {

                    var options:Array = [];

                    for (var j:int = 0; j < tileset.length; j++){
                        if (tileset[j].hitTestObject(enemy) && ! tileset[j].tileMiddle.hitTestObject(player)) {
                            //trace(tileset[j].currentFrameLabel, tileset[j].hitTestObject(enemy));
                            tileset[j].outline.gotoAndStop("attack");
                            options.push(tileset[j]);
                        }

                        if (options.length > 0){
                            var enemyPick:int = Math.floor(Math.random()*options.length)

                        }

                    }
                    trace(enemyPick, options);
            }

Solution

  • First, create an array who's length is the maximum number of acceptable tiles. For instance, in a straight line of tiles, only two can possibly be available at a time. Now, each time you need to have the enemy move tiles, initialize a counter to 0. Then, loop through each tile, and 'ask' if it is touching the enemy. If it its, record it in array[counter], and increment counter. After the loop, pick a random number from 0 to (counter) and use array[random number] as the tile that the enemy moves to.