<1>由来:
在做一些需求的时候,我们可能需要把地图划分成均匀网格,随机找一个格子A,需要取到这个A格子九宫格内的所有格子索引
例如我们把地图划分成3x3网格(从左下开始 行向Y轴正方向延伸 列向X轴正方形延伸)
用int表示每个格子索引
7 8 9
4 5 6
1 2 3
用int[2]表示每个格子索引
3,1 3,2 3,3
2,1 2,2 2,3
1,1 1,2 1,3
例如:
此时我们需要知道7(或者表示为2,2)的九宫格,均匀网格定义为:行=4 列=5
16 17 18 19 20
11 12 13 14 15
6 7 8 9 10
1 2 3 4 5
List<int> lst = nineUtils.getNineGrid(7);或者List<int> lst= nineUtils.getNineGrid(2,2);
结果为 13 8 3 2 1 6 11 12
List<int> lst = nineUtils.getNineGrid(10);或者List<int> lst= nineUtils.getNineGrid(2,5);
结果为 5 4 9 14 15
public class NineUtils
{
//定义8方向 顺时针
public Dictionary<int, int[]> dirMap = new Dictionary<int, int[]>
{
{ 1 ,new int[2]{ 1,1} },
{ 2 ,new int[2]{ 0,1} },
{ 3 ,new int[2]{ -1,1} },
{ 4 ,new int[2]{ -1,0} },
{ 5 ,new int[2]{ -1,-1} },
{ 6 ,new int[2]{ 0,-1} },
{ 7 ,new int[2]{ 1,-1} },
{ 8 ,new int[2]{ 1,0} },
};
//定义行和列
public int rowNum = 4;
public int colNum = 5;
public List<int> getNineGrid(int index)
{
int row = getRow(index);
int col = getCol(index);
return getNineGrid(row, col);
}
public List<int> getNineGrid(int[] rw)
{
return getNineGrid(rw[0], rw[1]);
}
public List<int> getNineGrid(int row, int col)
{
List<int> indexMap = new List<int>();
int[] delta = new int[2];
foreach (var item in dirMap)
{
int[] xy = item.Value;
delta[0] = xy[0] + row - 1;
delta[1] = xy[1] + col;
if (isVaildIndex(delta))
{
indexMap.Add(delta[0] * colNum + delta[1]);
}
}
return indexMap;
}
private int getRow(int index)
{
return Mathf.CeilToInt((index - 0.1F) / colNum);
}
private int getCol(int index)
{
int col = index % colNum;
return col == 0 ? colNum : col;
}
//验证合法性
private bool isVaildIndex(int[] xy)
{
return xy[0] >= 0 && xy[0] < rowNum && xy[1] > 0 && xy[1] <= colNum;
}
}
贴一个之前写的版本(Lua写的 有点恶心)
--获取格子周围所有格子
function BattleRoyaleDropMgr:getRoundIndex(index)
local lst = {}
--top 没有上 r1r2r3 --bottom没有下 r6r7r8 --left没有左r1r4r6 --right没有右r3r5r8
local isTop = index<=maxRow
local isBottom = index > (maxCol-1)*maxRow
local isLeft = index%maxRow == 1
local isRight = index%maxRow == 0
local filter = {}
local r1 = index - maxRow - 1
local r2 = index - maxRow
local r3 = index - maxRow + 1
local r4 = index - 1
local r5 = index + 1
local r6 = index + maxRow - 1
local r7 = index + maxRow
local r8 = index + maxRow + 1
if isTop then
filter[r1] = true
filter[r2] = true
filter[r3] = true
end
if isBottom then
filter[r6] = true
filter[r7] = true
filter[r8] = true
end
if isLeft then
filter[r1] = true
filter[r4] = true
filter[r6] = true
end
if isRight then
filter[r3] = true
filter[r5] = true
filter[r8] = true
end
local result = {r1,r2,r3,r4,r5,r6,r7,r8}
for i =1,#result do
if filter[result[i]] == nil then
lst[result[i]] = true
end
end
lst[index] = true
return lst
end