Exemplo n.º 1
0
 public PCell(IntVector2 pos, int generation, float heuristic, PCell parent)
 {
     this.pos        = pos;
     this.generation = generation;
     this.heuristic  = heuristic;
     this.parent     = parent;
 }
Exemplo n.º 2
0
    //A*寻路:根据起点和目标点 得到触手路径
    private List <IntVector2> FindTentaclePath(IntVector2 start, IntVector2 goal)
    {
        //开放列表
        List <PCell> openLst = new List <PCell>()
        {
            new PCell(goal, 0, 0.0f, null)
        };

        //关闭列表
        bool[,] closeTags = new bool[room.TileWidth, room.TileHeight];

        //从目标点向起始点寻路
        PCell tempCell = null;

        while (openLst.Count > 0 && tempCell == null)
        {
            //选取开放列表中启发代价最小的单元
            PCell parent = openLst[0];
            float minH   = float.MaxValue;
            for (int index = 0; index < openLst.Count; ++index)
            {
                if (openLst[index].heuristic < (double)minH)
                {
                    parent = openLst[index];
                    minH   = openLst[index].heuristic;
                }
            }
            openLst.Remove(parent);
            //四方向检测
            for (int index = 0; index < 4; ++index)
            {
                //左右边界、上下边界和关闭列表检测
                if (parent.pos.x + Utils.fourDirections[index].x >= 0 && parent.pos.x + Utils.fourDirections[index].x < room.TileWidth &&
                    (parent.pos.y + Utils.fourDirections[index].y >= 0 && parent.pos.y + Utils.fourDirections[index].y < room.TileHeight) &&
                    !closeTags[parent.pos.x + Utils.fourDirections[index].x, parent.pos.y + Utils.fourDirections[index].y])
                {
                    //计算寻路代价(Solid:1000)
                    float heuristic = Vector2.Distance(IntVector2.ToVector2(parent.pos + Utils.fourDirections[index]), IntVector2.ToVector2(start)) + (!room.GetTile(parent.pos + Utils.fourDirections[index]).Solid ? 0.0f : 1000f);
                    //创建新的Pcell
                    PCell pcell = new PCell(parent.pos + Utils.fourDirections[index], parent.generation + 1, heuristic, parent);
                    //设置重复检测标志位
                    closeTags[parent.pos.x + Utils.fourDirections[index].x, parent.pos.y + Utils.fourDirections[index].y] = true;
                    //寻到路径:退出循环
                    if (pcell.pos == start)
                    {
                        tempCell = pcell;
                    }
                    else
                    {
                        openLst.Add(pcell);
                    }
                }
            }
        }
        //逆转列表获得寻路结果
        List <IntVector2> pathLst = new List <IntVector2>();

        for (; tempCell.parent != null; tempCell = tempCell.parent)
        {
            pathLst.Add(tempCell.pos);
        }
        return(pathLst);
    }