4

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

为了更好地理解: 替代文字

4

3 回答 3

0

这是我对路径上最近点的 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;
}
于 2013-02-14T09:17:27.263 回答
-1

Are you wanting to calculate this in order to say something like "if the point-to-path distance is zero, then remove the point"? If so, then there is probably an easier way to remove redundant nodes. Take the points three at a time (call them A, B, and C). Calculate the angle between A and B, as well as the angle between B and C. If the two angles are the same, then point B lies in the path between A and C and is redundant. You can use the 'atan2' function (or your language's equivalent) to do the angle calculations.

于 2010-08-31T18:00:44.087 回答
-1

这是游戏中常用的一种点对点寻路算法:

A* 搜索算法

您可能需要在您的点和路径之间多次应用它,但它通常非常快。该算法对地图网格(正方形之间的距离为整数)进行了一些优化。对此有描述:Real-Time Strategy Game Programming using MS DirectX 6.0 by Mickey Kawick。

Djikstra 算法是一种很好的通用寻路算法,从单个源节点到图中的所有其他节点。当你找到你需要的东西时,你可以停止算法——在你的情况下,当算法找到到路径上每个节点的最短路径时。

我不知道特定的“从节点到路径的最短路径”算法。

于 2010-08-31T12:44:45.160 回答