Skip to content

Commit 249fe58

Browse files
committed
Tileset: tile lookup features
1 parent 5d25e10 commit 249fe58

1 file changed

Lines changed: 88 additions & 0 deletions

File tree

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
var Class = require('../../utils/Class');
2+
3+
var Tileset = new Class({
4+
5+
initialize:
6+
7+
function Tileset (name, firstgid, tileWidth, tileHeight, tileMargin, tileSpacing, properties)
8+
{
9+
if (tileWidth === undefined || tileWidth <= 0) { tileWidth = 32; }
10+
if (tileHeight === undefined || tileHeight <= 0) { tileHeight = 32; }
11+
if (tileMargin === undefined) { tileMargin = 0; }
12+
if (tileSpacing === undefined) { tileSpacing = 0; }
13+
14+
this.name = name;
15+
this.firstgid = firstgid;
16+
this.tileWidth = tileWidth;
17+
this.tileHeight = tileHeight;
18+
this.tileMargin = tileMargin;
19+
this.tileSpacing = tileSpacing;
20+
this.properties = properties;
21+
this.image = null;
22+
this.rows = 0;
23+
this.columns = 0;
24+
this.total = 0;
25+
this.texCoordinates = [];
26+
},
27+
28+
setImage: function (texture)
29+
{
30+
this.image = texture;
31+
this.updateTileData(this.image.source[0].width, this.image.source[0].height);
32+
},
33+
34+
containsTileIndex: function (tileIndex)
35+
{
36+
return (
37+
tileIndex >= this.firstgid &&
38+
tileIndex < (this.firstgid + this.total)
39+
);
40+
},
41+
42+
getTileTextureCoordinates: function (tileIndex)
43+
{
44+
if (!this.containsTileIndex(tileIndex)) { return null; }
45+
return this.texCoordinates[tileIndex - this.firstgid];
46+
},
47+
48+
updateTileData: function (imageWidth, imageHeight)
49+
{
50+
var rowCount = (imageHeight - this.tileMargin * 2 + this.tileSpacing) / (this.tileHeight + this.tileSpacing);
51+
var colCount = (imageWidth - this.tileMargin * 2 + this.tileSpacing) / (this.tileWidth + this.tileSpacing);
52+
53+
if (rowCount % 1 !== 0 || colCount % 1 !== 0)
54+
{
55+
console.warn('Tileset ' + this.name + ' image tile area is not an even multiple of tile size');
56+
}
57+
58+
// In Tiled a tileset image that is not an even multiple of the tile dimensions
59+
// is truncated - hence the floor when calculating the rows/columns.
60+
rowCount = Math.floor(rowCount);
61+
colCount = Math.floor(colCount);
62+
63+
this.rows = rowCount;
64+
this.columns = colCount;
65+
66+
// In Tiled, "empty" spaces in a tileset count as tiles and hence count towards the gid
67+
this.total = rowCount * colCount;
68+
69+
this.texCoordinates.length = 0;
70+
71+
var tx = this.tileMargin;
72+
var ty = this.tileMargin;
73+
74+
for (var y = 0; y < this.rows; y++)
75+
{
76+
for (var x = 0; x < this.columns; x++)
77+
{
78+
this.texCoordinates.push({ x: tx, y: ty });
79+
tx += this.tileWidth + this.tileSpacing;
80+
}
81+
82+
tx = this.tileMargin;
83+
ty += this.tileHeight + this.tileSpacing;
84+
}
85+
}
86+
});
87+
88+
module.exports = Tileset;

0 commit comments

Comments
 (0)