gpt4 book ai didi

path - 点到路径的最短距离

转载 作者:行者123 更新时间:2023-12-01 05:42:00 26 4
gpt4 key购买 nike

对于基于地理的在线游戏,我正在寻找一种算法,该算法可以找到指定点和由 x/y 坐标连接的已知路径之间的最短距离,以便我可以删除所有冗余点/节点。此算法的链接或关键字对我有很大帮助!谢谢阅读

为了更好地理解:
alt text

最佳答案

这是我对路径上最近点的 Java 实现

private Point getNearestPoint(Point from, List<Point> to_path) {

int count = to_path.size();

if (count == 0)
return null;
if (count == 1)
return to_path.get(0);

double nearest_dist = Double.MAX_VALUE;
Point nearest_point = null;

for (int i = 1; i < count; i++) {

Point p1 = to_path.get(i-1);
Point p2 = to_path.get(i);

Point p = getNearestPointOnSegment(from, p1, p2);
if (p != nearest_point) {
double dist = dist(from, p);
if (dist < nearest_dist) {
nearest_dist = dist;
nearest_point = p;
}
}
}

return nearest_point;
}

private Point getNearestPointOnSegment(Point from, Point p1, Point p2) {

if (dist(p1, p2) < 1e3) {
Log.d(TAG, "Points are near");
return p1;
}

double d2 = dist2(p1, p2);
double t = ((from.x - p1.x) * (p2.x - p1.x) + (from.y - p1.y) * (p2.y - p1.y)) / d2;

if (t < 0) {
//Log.d(TAG, "p1");
return p1;
}
if (t > 1) {
//Log.d(TAG, "p2");
return p2;
}

//Log.d(TAG, "t:" + t);
return new Point((int)(p1.x + t * (p2.x - p1.x)),
(int)(p1.y + t * (p2.y - p1.y)));
}

private double dist(Point p1, Point p2) {
return Math.sqrt(dist2(p1, p2));
}

private double dist2(Point p1, Point p2) {
return sqr(p1.x - p2.x) + sqr(p1.y - p2.y);
}

private double sqr(double x) {
return x * x;
}

关于path - 点到路径的最短距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3609049/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com