首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 開發 WPF/Silverlight 動畫與遊戲系列教程(七)傳說中的 A* 尋路算法(三)—— 尋路邏輯整合與測試

     編輯:關於C語言

尋路邏輯實作

private void Carrier_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) {
    Point p = e.GetPosition(Carrier);
    int x = (int)p.X / GridSize;
    int y = (int)p.Y / GridSize;
    End = new System.Drawing.Point(x, y);

    PathFinder = new PathFinderFast(Matrix);
    PathFinder.Formula = HeuristicFormula.Manhattan;
    PathFinder.SearchLimit = 2000;

    List<PathFinderNode> path = PathFinder.FindPath(Start, End);

    if (path == null) {
        MessageBox.Show("路徑不存在!");
    } else {
        string output = string.Empty;
        for (int i = path.Count - 1; i >= 0; i--) {
            output = string.Format(output + "{0}" + path[i].X.ToString() + "{1}" + path[i].Y.ToString() + "{2}", "(", ",", ") ");
            rect = new Rectangle();
            rect.Fill = new SolidColorBrush(Colors.Green);
            rect.Width = GridSize;
            rect.Height = GridSize;
            Carrier.Children.Add(rect);
            Canvas.SetLeft(rect, path[i].X * GridSize);
            Canvas.SetTop(rect, path[i].Y * GridSize);
        }
        MessageBox.Show("路徑坐標分別為:" + output);
    }
}

滑鼠點擊點作為動態終點,建立尋路器 PathFinder,設定曼哈頓啟發式、搜尋上限 2000 步,呼叫 FindPath 獲取路徑節點列表。綠色方塊標記路徑,彈窗顯示座標序列。

程式運行圖:綠色為尋得路徑,紅色為障礙物。複雜迷宮中 3ms 找到最佳路徑,極其優異。

下節預告

將介紹如何用取得的 List<PathFinderNode> path 實現動態關鍵幀動畫移動,敬請期待。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved