簡體   English   中英

二維空間中的尋路

[英]Path-finding in 2D space

我正在創建一個游戲,我希望敵人能夠追蹤到玩家——玩家可以在 2D 平面上向任何方向移動。 一開始,我嘗試...

self.bat_x += (player_rect.centerx - self.rect.centerx) / 60
self.bat_y += (player_rect.centery - self.rect.centery) / 60

在這里,路徑跟蹤工作正常。 我將每個值除以 60,這樣敵人就不會只是出現並粘在我的播放器上 / 以減慢敵人的移動速度。 然而,敵人越遠,它的速度就越快。 球拍越近,球拍的速度就越慢。 這是因為,例如使用 x 軸,當玩家和敵人之間的距離更小時, player_rect.centerx - self.rect.centerx更小,因此添加到self.bat_x的更少。 有沒有辦法讓尋路仍然有效但速度恆定? 或者有誰知道不同的尋路方法以及如何實現它?

一種方法是使用玩家和敵人的位置來找到連接它們的線的斜率/角度。

考慮到敵人在 (x1, y1) 而玩家在 (x2, y2)。 然后

angle = arctan((y2 - y1)/x2-x1))

請注意,x2 - x1 可能為零,因此請注意這種情況。

找到線后,您可以使用極坐標找到下一個 position

例如

x += speed * sin(angle)
Y += speed * cos(angle)

畢達哥拉斯是你的朋友

x = player_rect.centerx - self.rect.centerx
y = player_rect.centery - self.rect.centery
norm = (x**2 + y**2)**0.5
const = 1/60
self.bat_x += const * x / norm
self.bat_y += const * y / norm

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM