posts - 72,  comments - 4,  trackbacks - 0
unity slg的方形和六边形测试, 其中主要是坐标转换,下面是我自己想出来的一种比较简便高效的处理方法,实现方法如下:
   
    // 记录下: 这是我看图总结出的比较简便的算法:)(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));
            // 得到格子左下角坐标:
            float OGX = iGX * (2 * halfGridWidth);
            float OGY = iGY * (1.5f * edgeLength);
            float refX = OGX + halfGridWidth;
            float refY = OGY + edgeLength * 0.5f;
            // 可能不在本格子内(因为可能位置在格格子下方的左下角或右下角):
            bool bOutProbably = yWorld < refY;
            if (bOutProbably)
            {
                // 得到Hex中心往下半个外边长的位置:
                float dx = Mathf.Abs(xWorld - refX) * (0.5f * edgeLength / halfGridWidth); // 乘( ../.. )使其变成正方形再来判断
                float dy = Mathf.Abs(yWorld - refY);
                float dt = dx + dy;
                // 在左半边:
                if (xWorld < refX)
                {
                    // 不在本格子,而是在左下角:
                    if (dt > edgeLength * 0.5f)
                    {
                        iGY--; // 不管奇偶,下部都要y--
                               // 如果是偶数的左下,还要将x--
                        if (false == odd)
                        {
                            iGX--;
                        }
                    }
                }
                // 在右半边
                else
                {
                    // 不在本格子, 而是在右下角:
                    if (dt > edgeLength * 0.5f)
                    {
                        iGY--; // 不管奇偶,下部都要y--
                               // 如果是奇数的右下,还要将x++
                        if (odd)
                        {
                            iGX++;
                        }
                    }
                }
            }
            return new Vector2(iGX, iGY);
        }
        public static Vector3 ToWorldPos(int iGX, int iGY)
        {
            bool odd = ((iGY & 1) != 0);
            // 得到格子左下角坐标:
            float OGX = iGX * (2 * halfGridWidth);
            float OGY = iGY * (1.5f * edgeLength);
            // 奇数行要右移半个宽度:
            if (odd)
            {
                OGX += halfGridWidth;
            }
            // 偏移转到格子中心位置:
            Vector3 pos = new Vector3(OGX + halfGridWidth, 0, OGY + edgeLength);
            return pos;\
        }

下面是我画的图,非常丑,将就看

b附上测试图,已带ai移动攻击, 不过图看不到:
posted on 2020-01-03 18:09 flipcode 阅读(1278) 评论(0)  编辑 收藏 引用

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理