我一直在研究用Java编辑图块集和地图编辑。但是,我遇到了一个问题。
地图文件指定要放置的切片,如下所示:
tileset image: tiles.png
tileset width: 1024
tileset height: 1024
tileset tile width: 16
tileset tile heigth: 16
tiles on x axis: 5
tiles on y axis: 6
tiles: 1,1,1,1,1,1,1,1,1,1,1,1,3,2,2,2,2,2,22,3,4,26,21,9,19,28,18,2,1,1,1,1 etc...
将读取图块集图像,如下所示:
X:
1 - 2 - 3 - 4 - 5
-----------------------
1| 1 | 2 | 3 | 4 | 5
2| 6 | 7 | 8 | 8 | 10
Y:3| 11| 12| 13| 14| 15
4| 16| 17| 18| z | 20
5| 21| 22| 23| 24| 25
6| 26| 27| 28| 29| 30
("|"s 仅用于间距)
为了帮助理解此表,"z"处的图块集 x,y 坐标为 (4,4),其索引为 19。
现在忘记图像,因为它们在这里无关紧要,我想知道如何从 tilset 上的坐标(z 的 (4,4))获取索引(z 的 19)。
例如,如果我有这个代码:
int tilesetTilesWidth = tilesetImageWidth / tileWidth;
int tilesetTilesHeight = tilesetImageHeight / tileHeight;
int[][] coords = new int[tilesetTilesWidth][tilesetTilesHeight];
int[] indexes = new int[tilesetTilesWidth * tilesetTilesHeight];
for(int x = 0; x < coords.length; x++){
for(int y = 0; y < coords[x].length; y++){
indexes[?] = coords[x][y]; //What should ? or this line be replaced with?
}
}
应该用什么?或这一行替换?
注意:如果有任何问题或我错过了什么,请发表评论,因为我很着急。
安德森的答案可能是你要找的,但只是为了回答这个问题,我相信索引会(y-1)*cords.length+x
.
例子中,由于cords.length = 5,y=4和x=4,我们将根据需要得到(4-1)*5+4 = 3*5+4 = 15 + 4 = 19。
您也可以尝试:
for(int i = 0; i < tilesetTilesWidth * tilesetTilesHeight; i++) {
indexes[i] = coords[i%tilesetTilesWidth][i/tilesetTilesHeight];
}
此方法使用模算术,并给出相同的结果。
注意:有关模算术的更多信息:
- 罗格大学数学系
- 维基百科
例如,您可以创建第三个索引,k
,并在每次将新值插入indexes
时递增它:
for (int x = 0, k = 0; x < coords.length; x++) {
for (int y = 0; y < coords[x].length; y++) {
indexes[k++] = coords[x][y];
}
}
您不需要创建用于访问 Z(x, y) 的矩阵。
只需使用 Tile[(y-1)*w+x] ,它就会给你 x, y 处的元素
tWidth = 5;
tHeight = 6; // you don't need this for accessing (x, y)
tile = [1,1,1,1,1,1,1,1,1,1,1,1,3,2,2,2,2,2,22,3,4,26,21,9,19,....]
function get(X, Y) = tile[(Y-1)*tWidth + X];