Ejemplo n.º 1
0
    private void InitHex()
    {
        int      cols   = 20;
        int      rows   = 20;
        int      size   = 5;
        int      type   = OffsetCoord.POINTY;
        int      offset = OffsetCoord.ODD;
        HexAStar astar  = new HexAStar();
        HexGrid  grid   = new HexGrid();

        astar.grid = grid;
        hexObjects = new List <HexObject>();

        for (int x = 0; x < cols; x++)
        {
            for (int y = 0; y < rows; y++)
            {
                OffsetCoord offsetCoord = new OffsetCoord(x, y);
                Hex         hex         = type == OffsetCoord.FLAT ? OffsetCoord.GetCubeFromQOffsetCoord(offset, offsetCoord) : OffsetCoord.GetCubeFromROffsetCoord(offset, offsetCoord);
                Vector2     point       = type == OffsetCoord.FLAT ? OffsetCoord.GetQPixelFromOffsetCoord(offset, offsetCoord, size) : OffsetCoord.GetRPixelFromOffsetCoord(offset, offsetCoord, size);
                HexObject   hexObject   = new HexObject();
                hexObject.offsetCoord = offsetCoord;
                hexObject.hex         = hex;
                hexObject.point       = point;
                hexObject.transform.SetParent(GameObject.Find("HexMap").transform, false);
                hexObject.transform.rotation      = Quaternion.Euler(90f, 0, 0);
                hexObject.transform.localScale    = new Vector3(0.05f, 0.05f, 0.05f);
                hexObject.transform.localPosition = new Vector3(point.x, 0, point.y);
                hexObject.renderer.color          = new Color(hexObject.renderer.color.r, hexObject.renderer.color.g, hexObject.renderer.color.b, 0.2f);
                //hexObject.transform.localPosition = new Vector3(point.x, point.y);
                hexObjects.Add(hexObject);
                bool moveable = Random.Range(0f, 1f) > 0.25f ? true : false;
                grid.AddNode(hex, moveable);
            }
        }

        while (true)
        {
            int       index     = MathUtil.RandomRangeInt(0, hexObjects.Count - 1);
            HexObject hexObject = hexObjects[index];
            HexNode   node      = grid.GetNode(hexObject.hex);
            if (node.moveable)
            {
                grid.SetStartNode(node);
                break;
            }
        }

        {
            HexObject hexObject = hexObjects[MathUtil.RandomRangeInt(0, hexObjects.Count - 1)];
            HexNode   node      = grid.GetNode(hexObject.hex);
            grid.SetEndNode(node);
        }

        List <HexNode> path = astar.Find(grid.startNode.hex, grid.endNode.hex);

        if (path != null)
        {
            Debug.Log("开始寻路:");
            foreach (HexNode node in path)
            {
                Debug.Log(node.hex);
            }
        }
        else
        {
            Debug.Log("路径为空:");
        }
    }