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 實現動態關鍵幀動畫移動,敬請期待。