【一種獲取九宮格index的方式】
阿新 • • 發佈:2019-05-09
mgr function public add 正方形 stop ron spa --
<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
【一種獲取九宮格index的方式】