二维空间中的寻路 [英] Path-finding in 2D space

查看:103
本文介绍了二维空间中的寻路的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个游戏,我希望敌人追踪到玩家身上-玩家可以在2D平面上的任何方向上移动.起初,我尝试过...

I am creating a game where I want an enemy to path track onto the player - who can move in any direction on the 2D plane. At first, I tried...

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的数量较少.有没有一种方法可以使寻路仍然有效,但速度是恒定的?还是有人知道另一种寻路方法以及如何实现它?

Here the path-tracking works fine. I divide each value by 60 so that the enemy doesn't just appear and stick on to my player / to slow the movement of the enemy down. However, the further away the enemy is, the faster it is. The closer the bat gets, the slower the bat gets. This is because, using the x-axis for example, when the distance between the player and the enemy is smaller, player_rect.centerx - self.rect.centerxis smaller so less gets added to self.bat_x. Is there a way so that the path-finding still works but the speed is constant? Or does anyone know a different path-finding method and how to implement it?

推荐答案

一种方法是使用玩家和敌人的位置来找到连接它们的直线的坡度/角度.

One way would be using the locations of the player and enemy to find the slope/angle of the line connecting them.

考虑到敌人位于(x1,y1),玩家位于(x2,y2). 然后

Considering that enemy is at (x1, y1) and player is at (x2, y2). Then

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

请注意x2-x1可能为零,因此请注意这种情况.

Note that x2 - x1 could be zero, so take care of that case.

找到线后,可以使用极坐标找到下一个位置

After finding the line, you could use polar coordinates to find the next position

例如

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

这篇关于二维空间中的寻路的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆