yltang Posted November 3, 2015 Share Posted November 3, 2015 Having been searching around, but couldn't find a solution. I am working on tilemaps. I would like to place a target on one of the safe tiles randomly for the player to collect. How would I do it? The following is what I'm getting so far. Please advise, thanks....this.map = game.add.tilemap('map');this.map.addTilesetImage('tiles', 'tiles');this.layer = this.map.createLayer('Tile Layer 1');this.map.setCollision(20, true, this.layer);// Supposing the safe tile number is 1, how do I randomly select a safe tile?this.safeTile = 1; Link to comment Share on other sites More sharing options...
jmp909 Posted November 3, 2015 Share Posted November 3, 2015 doesn't seem to be an option to get an array of tiles by index, so create an array of safeTile's up front (faster to search through during the game) by searching through the map for tiles with index 1... and then picking a random item from that array later i havent checked this code but it looks about rightvar safeTileIndex=1var safeTiles = []var tiles = layer1.getTiles(0,0, layer1.width, layer1.height)tiles.forEach(function(tile) { if(tile.index==safeTileIndex) { safeTiles.push(tile) }})var tile = Phaser.ArrayUtils.getRandomItem(tiles)console.log(tile, tile.x, tile.y, tile.worldX, tile.worldY) yltang 1 Link to comment Share on other sites More sharing options...
yltang Posted November 3, 2015 Author Share Posted November 3, 2015 Thanks a lot. However, the variable "safeTileIndex" doesn't seem to be accessible from the function of "tiles.forEach(...)". I don't know why and I end up with the followingfor (var i=0; i<tiles.length; i++) { if (tiles[i].index==safeTileIndex) { safeTiles.push(tiles[i]); }} Link to comment Share on other sites More sharing options...
Clowerweb Posted November 3, 2015 Share Posted November 3, 2015 Thanks a lot. However, the variable "safeTileIndex" doesn't seem to be accessible from the function of "tiles.forEach(...)". I don't know why and I end up with the followingfor (var i=0; i<tiles.length; i++) { if (tiles[i].index==safeTileIndex) { safeTiles.push(tiles[i]); }} It's out of scope. Try this instead:// make these properties instead of variablesthis.safeTileIndex = 1;this.safeTiles = [];this.tiles = layer1.getTiles(0,0, layer1.width, layer1.height);this.tiles.forEach(function(tile) { if(tile.index === this.safeTileIndex) { this.safeTiles.push(tile) }}, this); // pass the parent object into the scope of the forEach methodNow you should be able to access the properties from within the forEach. yltang, jmp909 and hoskope 3 Link to comment Share on other sites More sharing options...
Recommended Posts