Jump to content
This forum will be closing down. Please move to the respective dedicated project forums.

How to count how many tiles are there in a layer


thefootballguy
 Share

Recommended Posts

On 8/27/2014 at 3:12 PM, Guybrush said:

this works without any error for me even with null objects in the map.


for(var y = 0; y < map.height; ++y){   for(var x = 0; x < map.width; ++x){      var tile = map.getTile(x, y);      console.log(tile);   }}

I found this ^ for looping through all the map. However, I just want to count how many tiles are there at the moment. Any help will be helpful friends.

Link to comment
Share on other sites

function howMany (map) {
  var count = 0
  for(var y = 0; y++; y < map.height) {
    for(var x = 0; x++; x < map.width) {
      count++
    }
  }
  return count
}

Thats a basic solution that would work fine.

However, if you know the height and width and, crucially, you know you are not working with a sparse tile map then

var count = map.width * map.height

If your map is sparse and you want to query the total number of tiles often then its probably worth caching the count inside your map, something along the lines of

var map = {
  width: 20,
  height: 20,
  count: 0,
  tiles: createEmptyTilemap()
  
  addTile: function(x, y, tile) {
   count++
    tiles[x][y] = tile
  },
 
  removeTile: function(x, y) {
    count--
    tiles[x][y] = null
  }
}

2d arrays (an array of arrays) are kind of a bit rubbish, its not a particularly efficient data structure and its fairly clunky to work with. A 1d array with some meta to describe its width is better, that way you can still use 2d lookups if you want but you have a slightly easier structure to work with underneath, of course, if your array is sparse you'll still have lots of redundant tiles.

If your tile map is sparse then you might want to simply use a list (an array) and only insert 'live' tiles, this means that each tile would need to have its own positional data and you'd either have to sort continually or not bother (there's seldom a requirement that it must be sorted).

If you have a multi-layer tilemap then you could make the assumption that the bottom layer is always filled but any tile can have any number of layers above that (items, more scenery, entities etc). It's tempting to use a 3d array for this but you can carry on with the 1d array, but have each tile contain data about the layers that it contains. This is the most efficient in terms of memory and can be more performant also but slightly more complex for the programmer.

Fun and games all this tiling stuff :) 

 

 

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...