我正在创建一个 2D TileMap。我使用整数来确定图块类型。我想将与至少一个海洋瓷砖 (3) 相邻的每一块草瓷砖 (4) 变成沙子 (1)。
public void geography() {
for(int x=0; x<width; x++) { //Iterates through array
for(int y=0; y<height; y++) {
int counter = sametile(x,y,1,3); // uses a method to count neighbouring tiles
if(counter>0 && map[x][y]==4) { //if it at least has 1
map[x][y]=1; //turns that tile into sand
}
}
}
}
public int sametile(int locx,int locy,int diameter,int tile) { //location x,y,search diameter and tile type
int counter=0;
for(int x=locx-diameter; x<locx+diameter; x++) { //where we start and end
for(int y=locy-diameter; y<locy+diameter; y++) {
if (x < diameter || y < diameter || x+diameter>width || y+diameter>height) {
counter++;
continue;
//to avoid reaching index numbers that array doesnt have
}
if(map[x][y]==tile) { //if it is the tile we are looking for
counter++; //we increase the counter
}
}
}
return counter;
}
奇怪的是它在地图的某些部分按预期工作,但在地图的某些部分部分错误或完全错误。
我确实检查了每一行代码,但没有真正发现任何东西
所以假设直径为 1,我想做的事情之一就是检查我的左边和右边。
for(int x=locx-diameter; x<locx+diameter; x++)
看这个是从我的左边开始,然后永远不会检查我的右边,因为它不使用
<=
。 y
和上面/下面的逻辑类似。
for(int y=locy-diameter; y<locy+diameter; y++) {
好的,现在如果 locx 是 1 并且我需要向左看,那么我需要在图块 0 处进行拍摄,但这会阻止这种情况:
if (x < diameter
对于其他边界也类似,所以我假设你想要:
if (x < 0 || y < 0 || x >= width || y >= height) {
counter++;
continue;
}