2016-10-26 119 views
1

我的遊戲中有2個目標。我正在使用廣度優先搜索來找到其中一個路徑。我想知道如何使用座標確定哪個是最接近的目標。我有我的目標(所有int類型)的X和Y座標。如何找到給定起點座標的最近目標?

int result = 0; 
int target1dist = (playerX - target1x) + (playerY - target1y); 
int target2dist = (playerX - target2x) + (playerY - target2y); 

if (target1dist < target2dist){ 
    result = BFS(target1x,target1y,playerX ,playerY); 
} else { 
    result = BFS(target2x,target2y,playerX ,playerY); 
} 

當一個目標的距離爲負值時,這並不奏效。所以我加了絕對值函數。所以target1dist和target2dist不能爲負數。

int target1dist =Math.abs ((playerX - target1x) + (playerY - target1y)); 

這是尋找最接近目標的有效方法,所以我的AI玩家可以直接瞄準它嗎? P.S:我的Ai玩家只能走4個方向,所以排除對角線。我的另一個想法是使用畢達哥拉斯來找到距離。

+0

所以問題是:它工作?我建議它(請參閱我的答案)。否則,你在這裏有一些完美的代碼示例(當然,在我的回答中也可以看到結果的初始化)。 – Igor

+0

@Igor是的。謝謝。但我想知道是否有最佳解決方案。比我的方式更好。 – Kadir

+0

好吧......我不明白怎麼樣,除非你可以從後面接近你的目標(做一個鉤子)。在這種情況下,距離較近的目標實際上可能比另一個更長。 – Igor

回答

0

稍作修改後,您的方法應該可以工作。你不想採取充分表達的絕對值,但每個組件:

int traget1dist = Math.abs(playerX - target1x) + Math.abs(playerY - target1y); 

這就是所謂的Manhattan distance,是基於搜索瓷磚作爲你的一個共同的測量。由於廣度優先搜索是guaranteed to find the optimal solution您的解決方案將工作。

相關問題