unity slg的方形和六邊形測(cè)試, 其中主要是坐標(biāo)轉(zhuǎn)換,下面是我自己想出來(lái)的一種比較簡(jiǎn)便高效的處理方法,實(shí)現(xiàn)方法如下:
// 記錄下: 這是我看圖總結(jié)出的比較簡(jiǎn)便的算法:)(flipcode@qq.com):
// 注意,傳入的xWorld要/edgeLength
public static Vector2 ToHexGrid(float xWorld, float yWorld)
{
float edgeLength = 1;
float halfGridWidth = edgeLength * 0.866025404f;
int iGY = (int)(yWorld / (1.5 * edgeLength));
bool odd = ((iGY & 1) != 0);
// 奇:
if (odd)
{
xWorld -= halfGridWidth;
}
int iGX = (int)(xWorld / (2 * halfGridWidth));
// 得到格子左下角坐標(biāo):
float OGX = iGX * (2 * halfGridWidth);
float OGY = iGY * (1.5f * edgeLength);
float refX = OGX + halfGridWidth;
float refY = OGY + edgeLength * 0.5f;
// 可能不在本格子內(nèi)(因?yàn)榭赡芪恢迷诟窀褡酉路降淖笙陆腔蛴蚁陆?:
bool bOutProbably = yWorld < refY;
if (bOutProbably)
{
// 得到Hex中心往下半個(gè)外邊長(zhǎng)的位置:
float dx = Mathf.Abs(xWorld - refX) * (0.5f * edgeLength / halfGridWidth); // 乘( ../.. )使其變成正方形再來(lái)判斷
float dy = Mathf.Abs(yWorld - refY);
float dt = dx + dy;
// 在左半邊:
if (xWorld < refX)
{
// 不在本格子,而是在左下角:
if (dt > edgeLength * 0.5f)
{
iGY--; // 不管奇偶,下部都要y--
// 如果是偶數(shù)的左下,還要將x--
if (false == odd)
{
iGX--;
}
}
}
// 在右半邊
else
{
// 不在本格子, 而是在右下角:
if (dt > edgeLength * 0.5f)
{
iGY--; // 不管奇偶,下部都要y--
// 如果是奇數(shù)的右下,還要將x++
if (odd)
{
iGX++;
}
}
}
}
return new Vector2(iGX, iGY);
}
public static Vector3 ToWorldPos(int iGX, int iGY)
{
bool odd = ((iGY & 1) != 0);
// 得到格子左下角坐標(biāo):
float OGX = iGX * (2 * halfGridWidth);
float OGY = iGY * (1.5f * edgeLength);
// 奇數(shù)行要右移半個(gè)寬度:
if (odd)
{
OGX += halfGridWidth;
}
// 偏移轉(zhuǎn)到格子中心位置:
Vector3 pos = new Vector3(OGX + halfGridWidth, 0, OGY + edgeLength);
return pos;\
}
下面是我畫(huà)的圖,非常丑,將就看

b附上測(cè)試圖,已帶ai移動(dòng)攻擊, 不過(guò)圖看不到:


下面是我畫(huà)的圖,非常丑,將就看

b附上測(cè)試圖,已帶ai移動(dòng)攻擊, 不過(guò)圖看不到:


