Jump to content

Bug loading tilemaps with margins/spacing?


Recommended Posts

Using a tileset image with these properties:

  • 432x396 image size
  • 32x32 tile size
  • 12x11 distinct tiles
  • 2px margin on all sides
  • 4px spacing between tiles

Tileset image is attached, annotated with red for margin pixels and green for spacing pixels.



When creating a tilemap based on this tileset, Phaser.Tileset warns that "image tile area is not an even multiple of tile size" in the function updateTileData. (Link to relevant lines of code in Phaser.) Then, when the tilemap is loaded, it displays the wrong tiles.


The offending calculation seems to be lines 217 and 218. The formula as written only accounts for the left/top margin pixels, but adding the right/bottom margin is important for checking whether the image is sized correctly or not. Furthermore, when counting rows and columns, the use of Math.floor at 227/228 does prevent loading of partial tiles if the image is in fact sized correctly, but in this case (where the margin is smaller than the spacing) it will actually cut off the last row and column of tiles.


With the current formula, the rowCount formula is:

var rowCount = (imageHeight - this.tileMargin) / (this.tileHeight + this.tileSpacing);


var rowCount = (432 - 2) / (32 + 4) = 11.94...5

This causes the "even multiple" warning. The Math.floor call at 227 then forces this value down to 11 rows, when in fact there are 12. This in turn causes Phaser to assign tile IDs incorrectly, which leads to the wrong tiles being displayed.


Changing the formula at 217/218 to the following will handle this case, while preserving the current version's ability to discard extraneous pixels:

var rowCount = (imageHeight - this.tileMargin * 2 + this.tileSpacing) / (this.tileHeight + this.tileSpacing);
var rowCount = (432 - 4 + 4) / (32 + 4) = 12
...which is the correct value, as confirmed by Tiled.
Since colCount works the same way, all of the above applies there.
See also this issue report, which resulted in the current version of the code. The change in the associated pull request fixed the issue, but didn't account for these margin/spacing issues.
Additional "test cases:"
  • 4 rows, 16px tiles, 0 margin, 0 spacing
    • Image height would be 64px
    • (64 - 0 + 0) / (16 + 0) = 4 rows
  • 4 rows, 16px tiles, 2 margin, 1 spacing
    • Image height would be 71px
    • (71 - 4 + 1) / (16 + 1) = 4 rows
This seems like just a bug, but I wanted to find out if someone is actually relying on the current behavior for some reason, and if you see any problem with the proposed fix.
Link to comment
Share on other sites

  • 3 weeks later...
  • 2 months later...

  • Recently Browsing   0 members

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