我在一个二维网格(x,y)上有一些点,需要找到所有距离该点n个单位长度的点。我使用两点之间的距离公式来测量距离。请问有人知道如何做到这一点吗?
编辑: 仅供参考,我的目标是编写一些AI路径规划,以在基于网格位置的系统中保持一定距离离目标。目前我正在使用A*路径规划,但我不确定它是否重要或有所区别,因为我对这方面的知识还比较新。
for each point
begin
if test 1 indicates the point is outside the outer bounding box,
then skip this point
if test 2 indicates the point is inside the inner bounding box,
then keep this point
if test 3 indicates the point is inside the radius of the circle,
then keep this point
end
这被称为最近邻搜索。更多信息请参见http://en.wikipedia.org/wiki/Nearest_neighbor_search。
有一些开源库可以实现这个功能。我使用过一个用C语言编写的库,推荐给大家:http://www.cs.umd.edu/~mount/ANN/。ANN代表近似最近邻,但是你可以关闭近似搜索,找到精确的最近邻。
这不会使用距离公式,但如果您正在寻找恰好相距n个距离的点,则可以使用sin/cos?
伪代码如下:
for degrees in range(360):
x = cos(degrees) * n
y = sin(degrees) * n
print x, y
这将以360度间隔打印每个n点。
Java 实现:
public static Set<Point> findNearbyPoints(Set<Point> pts, Point centerPt, double radius) {
Set<Point> nearbyPtsSet = new HashSet<Point>();
double innerBound = radius * (Math.sqrt(2.0) / 2.0);
double radiusSq = radius * radius;
for (Point pt : pts) {
double xDist = Math.abs(centerPt.x - pt.x);
double yDist = Math.abs(centerPt.y - pt.y);
if (xDist > radius || yDist > radius)
continue;
if (xDist > innerBound || yDist > innerBound)
continue;
if (distSq(centerPt, pt) < radiusSq)
nearbyPtsSet.add(pt);
}
return nearbyPtsSet;
}