Пример #1
0
        /// <summary>
        /// 寻路
        /// </summary>
        /// <param name="nodes">地图信息</param>
        /// <param name="start">起点</param>
        /// <param name="end">终点</param>
        /// <returns>路径是否存在</returns>
        public bool Search(Vector2 start, Vector2 end)
        {
            bool result = false;

            if (!m_nodes.ContainsKey(start) || !m_nodes.ContainsKey(end))
            {
                return(result);
            }
            if (m_nodes[start].type != NodeType.Movable || m_nodes[end].type != NodeType.Movable)
            {
                return(result);
            }

            //设置终点
            position_target = end;

            //重置路径
            for (int i = 0; i < t_nodes.GetLength(0); i++)
            {
                for (int j = 0; j < t_nodes.GetLength(1); j++)
                {
                    t_nodes[i, j].Reset();
                }
            }

            list_close.Clear();
            list_open.Clear();

            Node A = t_nodes[(int)start.x, (int)start.y];

            A.G      = 0;
            A.H      = Vector2.Distance(position_target, A.position);
            A.F      = A.G + A.H;
            A.parent = null;
            A.state  = NodeState.Close;

            list_close.Add(A);

            do
            {
                if (list_open.Count > 0)
                {
                    A = list_open[0];
                }
                for (int i = 0; i < list_open.Count; i++)
                {
                    if (list_open[i].F < A.F)
                    {
                        A = list_open[i];
                    }
                }

                if (A.Compare(position_target))
                {
                    result = true;
                }

                Node B = Search(A);

                if (B != null)
                {
                    do
                    {
                        B.type = NodeType.Route;
                        B      = B.parent;
                    }while (B != null);
                }
                list_close.Add(A);
                list_open.Remove(A);
                A.state = NodeState.Close;
            }while (list_open.Count > 0);

            return(result);
        }