您在评论中提到您正在尝试使用 2D int 数组执行此操作,所以我假设您的图块标有整数。假设您有一个包含所有整数的数组 int[,]。我还将假设您知道要查找邻居的图块的 x,y 位置。
假设您的数组看起来像这样,带有标记的索引:
[0,0] [1,0] [2,0] [3,0]
[0,1] [1,1] [2,1] [3,1]
[0,2] [1,2] [2,2] [3,2]
[0,3] [1,3] [2,3] [3,3]
如果你的数组被翻转,你需要翻转下面的一些逻辑,但它仍然适用。
要让瓷砖向西,它是 x-1。为了让瓷砖向东,它是 x+1。需要注意的是 x 不能大于 2D 数组的宽度,我们将其标记为 int widthOfArray。南北也一样,限制为 heightOfArray
让我们把它付诸实践:
//Assumption: [x,y] is the current array position that you want to find neighbors
//east and west are going to dictate your x index for finding the neighbor.
westIndex = Mathf.Clamp(x - 1, 0f, widthOfArray);
eastIndex = Mathf.Clamp(x + 1, 0f, widthOfArray);
//north and south are going to dictate your y index for finding the neighbor.
northIndex = Mathf.Clamp(y - 1, 0f, heightOfArray);
southIndex = Mathf.Clamp(y + 1, 0f, heightOfArray);
int northPoint = array[x, northIndex];
int northEastPoint = array[eastIndex, northIndex];
int eastPoint = array[eastIndex, y];
int southEastPoint = array[eastIndex, southIndex];
int southPoint = array[x, southIndex];
//...etc