在距离最近点的区域外的点?

时间:2011-11-12 08:38:29

标签: java 2d point area

我有一个程序,其中一个实体在二维空间中移动。要移动一步,实体会选择下一个点,然后将其设置为当前点。

然而,有时候,实体的下一个要点是禁止的Area(java.awt.geom.Area)(“禁区”实际上是速度障碍)。

实体如何选择最接近实体首选点的Area以外的点?

Area由不同的形状组成(有时,形状不接触)。

我最初的计划是简单地画一条线到首选点。无论线路首先与Area相交,这都是下一个最佳点。但是,找到一条线与Area之间的交点变得相当复杂。

编辑:这不一定能找到最接近的点。这只会在相同的轨迹上找到壁橱点。我正在寻找最接近的可能点。

也许Area不是最好的课程。我需要的是可以添加多个形状的东西,即使形状没有接触也是如此。

4 个答案:

答案 0 :(得分:2)

我已经解决了这个问题:

首先,找到约束Area的所有线段。我已经编写了代码on a different answer

然后,只需迭代每个线段,并记录最接近实体所需点的线段上的点。将它们存储在您选择的数据结构中(例如,ArrayList)。

请参阅:Shortest distance between a point and a line segment

最后,确定哪个点最接近所需点。瞧!

以下是演示:

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Area;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.geom.Path2D;
import java.awt.geom.PathIterator;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.Random;

import javax.swing.JFrame;

public class AreaTest extends JFrame{
    private static final long serialVersionUID = -2221432546854106311L;

    Area area = new Area();
    ArrayList<Line2D.Double> areaSegments = new ArrayList<Line2D.Double>();
    Point2D.Double insidePoint = new Point2D.Double(225, 225);
    Point2D.Double closestPoint = new Point2D.Double(-1, -1);
    Point2D.Double bestPoint = new Point2D.Double(-1, -1);
    ArrayList<Point2D.Double> closestPointList = new ArrayList<Point2D.Double>();

    AreaTest() {
        Path2D.Double triangle = new Path2D.Double();
        Random random = new Random();

        // Draw three random triangles
        for (int i = 0; i < 3; i++) {
            triangle.moveTo(random.nextInt(400) + 50, random.nextInt(400) + 50);
            triangle.lineTo(random.nextInt(400) + 50, random.nextInt(400) + 50);
            triangle.lineTo(random.nextInt(400) + 50, random.nextInt(400) + 50);
            triangle.closePath();
            area.add(new Area(triangle));
            triangle.reset();
        }

        // Place a point inside the area
        if (!area.contains(insidePoint)); {
            while (!area.contains(insidePoint)) {
                insidePoint.setLocation(random.nextInt(400) + 50, random.nextInt(400) + 50);
            }
        }

        // Note: we're storing double[] and not Point2D.Double
        ArrayList<double[]> areaPoints = new ArrayList<double[]>();
        double[] coords = new double[6];

        for (PathIterator pi = area.getPathIterator(null); !pi.isDone(); pi.next()) {

            // Because the Area is composed of straight lines
            int type = pi.currentSegment(coords);
            // We record a double array of {segment type, x coord, y coord}
            double[] pathIteratorCoords = {type, coords[0], coords[1]};
            areaPoints.add(pathIteratorCoords);
        }

        double[] start = new double[3]; // To record where each polygon starts
        for (int i = 0; i < areaPoints.size(); i++) {
            // If we're not on the last point, return a line from this point to the next
            double[] currentElement = areaPoints.get(i);

            // We need a default value in case we've reached the end of the ArrayList
            double[] nextElement = {-1, -1, -1};
            if (i < areaPoints.size() - 1) {
                nextElement = areaPoints.get(i + 1);
            }

            // Make the lines
            if (currentElement[0] == PathIterator.SEG_MOVETO) {
                start = currentElement; // Record where the polygon started to close it later
            } 

            if (nextElement[0] == PathIterator.SEG_LINETO) {
                areaSegments.add(
                        new Line2D.Double(
                            currentElement[1], currentElement[2],
                            nextElement[1], nextElement[2]
                        )
                    );
            } else if (nextElement[0] == PathIterator.SEG_CLOSE) {
                areaSegments.add(
                        new Line2D.Double(
                            currentElement[1], currentElement[2],
                            start[1], start[2]
                        )
                    );
            }
        }

        // Calculate the nearest point on the edge
        for (Line2D.Double line : areaSegments) {

            // From: https://stackoverflow.com/questions/6176227
            double u = 
              ((insidePoint.getX() - line.x1) * (line.x2 - line.x1) + (insidePoint.getY() - line.y1) * (line.y2 - line.y1))
            / ((line.x2 - line.x1) * (line.x2 - line.x1) + (line.y2 - line.y1) * (line.y2 - line.y1));

            double xu = line.x1 + u * (line.x2 - line.x1);
            double yu = line.y1 + u * (line.y2 - line.y1);

            if (u < 0) {
                closestPoint.setLocation(line.getP1());
            } else if (u > 1) {
                closestPoint.setLocation(line.getP2());
            } else {
                closestPoint.setLocation(xu, yu);
            }

            closestPointList.add((Point2D.Double) closestPoint.clone());

            if (closestPoint.distance(insidePoint) < bestPoint.distance(insidePoint)) {
                bestPoint.setLocation(closestPoint);
            }
        }

        setSize(new Dimension(500, 500));
        setLocationRelativeTo(null); // To center the JFrame on screen
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setResizable(false);
        setVisible(true);
    }

    public void paint(Graphics g) {
        // Fill the area
        Graphics2D g2d = (Graphics2D) g;
        g.setColor(Color.lightGray);
        g2d.fill(area);

        // Draw the border line by line
        g.setColor(Color.black);
        for (Line2D.Double line : areaSegments) {
            g2d.draw(line);
        }

        // Draw the inside point
        g.setColor(Color.red);
        g2d.fill(
                new Ellipse2D.Double(
                        insidePoint.getX() - 3,
                        insidePoint.getY() - 3,
                        6,
                        6
                        )
            );

        // Draw the other close points
        for (Point2D.Double point : closestPointList) {
            g.setColor(Color.black);
            g2d.fill(
                    new Ellipse2D.Double(
                            point.getX() - 3,
                            point.getY() - 3,
                            6,
                            6
                            )
                );
        }

        // Draw the outside point
        g.setColor(Color.green);
        g2d.fill(
                new Ellipse2D.Double(
                        bestPoint.getX() - 3,
                        bestPoint.getY() - 3,
                        6,
                        6
                        )
            );
    }

    public static void main(String[] args) {
        new AreaTest();
    }
}

结果如下:

enter image description here

再次:

enter image description here

答案 1 :(得分:0)

最简单(也是效率最低)的方法是蛮力。 你有一个区域内的首选点。找到最近的点:保持两个变量,一个用于最小距离,一个用于当前最近点。现在简单地跨过你的二维空间中的每一个点:如果那个点不在禁区内(或任何禁区,如果有很多),那么计算它与首选点之间的距离。如果该距离小于当前最小距离,则使其成为当前最小距离并使该点成为当前最近点。 完成后,您将获得该区域外最近的点,如果没有找到,则保持原点。

我不是几何算法的专家,但是如果二维空间非常大并且计算速度不够快,也许您可​​以尝试使用以下内容进行改进:Area类有一个包含“测试”的方法如果Shape的内部完全包含指定的矩形区域“。因此,开始在首选点周围创建矩形(或正方形)。你从点周围的最小矩形开始,在每个循环上,你在每个方向上增加一个点。对于您创建的每个矩形,检查它是否包含在该区域中。当您点击该区域中未完全包含的第一个矩形时,您将停止计算矩形。然后,你使用上面的算法(蛮力),但只使用这个矩形中包含的点,而不是在该区域内。

答案 2 :(得分:0)

两点之间的距离公式为(javascript):

var xDiff = ( point1x - point2x ),
    yDiff = ( point1y - point2y ),
    distance = Math.sqrt( ( xDiff * xDiff ) + ( yDiff * yDiff ) );

从一个x-1, y-1 to x+1, y+1开始绕过“建议的新点”。在每个点检查,看它不是一个禁止点,而不是你刚刚来的那个点,而不是地图的边界。如果它符合所有这些标准,请使用上面的公式来测量距离并将其添加到数组中。在“1点输出”循环结束时,检查该阵列中是否有任何距离。如果是这样,拿最小的一个就完成了。如果没有,请转到x-2, y-2 to x+2, y+2(2分)。

对于您所指的小区域,这将非常快。

演示:http://jsfiddle.net/ThinkingStiff/V7Bqm/

var X = 0, 
    Y = 1,
    currentPoint = [5,5],
    proposedPoint = [5,6],
    forbiddenPoints = [[5,6],[6,6],[4,7],[5,7],[6,7],[4,8],[5,8]],
    map = { left:1, top:1, right:10, bottom:10 };

function closestSafePoint( point ) {

    var x = point[X], y = point[Y], safePoints = [];

    for( var left = x - 1, top = y - 1, right = x + 1, bottom = y + 1;
         left <= map.left || top <= map.top || right <= map.right || bottom <= map.bottom;
         left--, top--, right++, bottom++) {

        checkHorizontalPoints( safePoints, point, left, right, top );
        checkHorizontalPoints( safePoints, point, left, right, bottom );
        checkVerticalPoints( safePoints, point, top + 1, bottom - 1, left );
        checkVerticalPoints( safePoints, point, top + 1, bottom - 1, right );

        safePoints.sort( function( a, b ){ return a[1] - b[1] } );

        return safePoints.length ? safePoints[0] : point;

    };

};

function checkHorizontalPoints( points, fromPoint, startX, endX, y ) {

    for( var x = startX; x <= endX ; x++ ) {

        var toPoint = [x, y];

        if( !isForbidden( toPoint ) && !isCurrent( toPoint) && onMap( toPoint ) ) {

            points.push( [toPoint, distance( fromPoint, toPoint )] );

        };

    };

};

function checkVerticalPoints( points, fromPoint, startY, endY, x ) {

    for( var y = startY; y <= endY ; y++ ) {

        var toPoint = [x, y];

        if( !isForbidden( toPoint ) && !isCurrent( toPoint) && onMap( toPoint ) ) {

            points.push( [toPoint, distance( fromPoint, toPoint )] );

        };

    };

};

function isForbidden( point ) {

    for( var index = 0; index < forbiddenPoints.length; index++ ) {

        if( forbiddenPoints[index].toString() == point.toString() ) return true;

    };

};

function isCurrent( point ) {

    return currentPoint.toString() == point.toString() ? true : false;

};

function onMap( point ) {

    var x = point[X], y = point[Y];
    return x >= map.left && y >= map.top && x <= map.right && y <= map.bottom;

};

function distance( pointA, pointB ) {

    var xDiff = ( pointA[X] - pointB[X] ),
        yDiff = ( pointA[Y] - pointB[Y] );

    return Math.sqrt( ( xDiff * xDiff ) + ( yDiff * yDiff ) );    

};

console.log( 
      'current: ' + currentPoint + ', '
    + 'proposed: ' + proposedPoint + ', '
    + 'closest: ' + closestSafePoint( proposedPoint )[0] 
);

你可以对此进行一次优化,如果你相当确定你的大部分安全点将是一两点,那么只要你到达距离与你的水平相同的点就会爆发'继续。因此,如果你在第一个循环中,并且你得到一个距离= 1的点,那就停下来吧,因为你永远不会比这更接近。

更新:我注意到你在问题中添加了“相同的轨迹”。但在其中一条评论中,你也说它无法跳过禁区。这些陈述似乎有冲突。

相同的轨迹有点棘手,需要一些触发。在http://jsfiddle.net/ThinkingStiff/uLu7v/查看我的循环div的演示。中途有一个“射线点”功能:

$this.siblings( ".circle" ).each( function()

计算将光线上的周围圆圈移离选定圆圈的距离。这可用于计算轨迹上的点。但是,我认为我的原始功能实际上是你正在寻找的,而你并不意味着相同的轨迹。

答案 3 :(得分:0)

this帖子

上查看我的回答

您可以使用简单轻巧的方法获取多边形外的最近点:

只需找到最近的线段,找到截取输入点的那个线段的垂直角度。

I don't need to describe it, just look at the image!

示例代码:

Vector2是2个双打,x和y(和Unity一样)

public class PolyCollisions {

    // Call this function...
    public static Vector2 doCollisions (Vector2[] polygon, Vector2 point) {

        if(!pointIsInPoly(polygon, point)) {
            // The point is not colliding with the polygon, so it does not need to change location
            return point;
        }

        // Get the closest point off the polygon
        return closestPointOutsidePolygon(polygon, point);

    }

    // Check if the given point is within the given polygon (Vertexes)
    // 
    // If so, call on collision if required, and move the point to the
    // closest point outside of the polygon
    public static boolean pointIsInPoly(Vector2[] verts, Vector2 p) {
        int nvert = verts.length;
        double[] vertx = new double[nvert];
        double[] verty = new double[nvert];
        for(int i = 0; i < nvert; i++) {
            Vector2 vert = verts[i];
            vertx[i] = vert.x;
            verty[i] = vert.y;
        }
        double testx = p.x;
        double testy = p.y;
        int i, j;
        boolean c = false;
        for (i = 0, j = nvert-1; i < nvert; j = i++) {
            if ( ((verty[i]>testy) != (verty[j]>testy)) &&
                    (testx < (vertx[j]-vertx[i]) * (testy-verty[i]) / (verty[j]-verty[i]) + vertx[i]) )
                c = !c;
        }
        return c;
    }

    // Gets the closed point that isn't inside the polygon...
    public static Vector2 closestPointOutsidePolygon (Vector2[] poly, Vector2 point) {

        return getClosestPointInSegment(closestSegment(poly, point), point);

    }

    public static Vector2 getClosestPointInSegment (Vector2[] segment, Vector2 point) {

        return newPointFromCollision(segment[0], segment[1], point);

    }

    public static Vector2 newPointFromCollision (Vector2 aLine, Vector2 bLine, Vector2 p) {

        return nearestPointOnLine(aLine.x, aLine.y, bLine.x, bLine.y, p.x, p.y);

    }

    public static Vector2 nearestPointOnLine(double ax, double ay, double bx, double by, double px, double py) {

        // https://stackoverflow.com/questions/1459368/snap-point-to-a-line-java

        double apx = px - ax;
        double apy = py - ay;
        double abx = bx - ax;
        double aby = by - ay;

        double ab2 = abx * abx + aby * aby;
        double ap_ab = apx * abx + apy * aby;
        double t = ap_ab / ab2;
        if (t < 0) {
            t = 0;
        } else if (t > 1) {
            t = 1;
        }
        return new Vector2(ax + abx * t, ay + aby * t);
    }

    public static Vector2[] closestSegment (Vector2[] points, Vector2 point) {

        Vector2[] returns = new Vector2[2];

        int index = closestPointIndex(points, point);

        returns[0] = points[index];

        Vector2[] neighbors = new Vector2[] {
                points[(index+1+points.length)%points.length],
                points[(index-1+points.length)%points.length]
        };

        double[] neighborAngles = new double[] {
                getAngle(new Vector2[] {point, returns[0], neighbors[0]}),
                getAngle(new Vector2[] {point, returns[0], neighbors[1]})
        };

        if(neighborAngles[0] < neighborAngles[1]) {
            returns[1] = neighbors[0];
        } else {
            returns[1] = neighbors[0];
        }

        return returns;

    }

    public static double getAngle (Vector2[] abc) {

        // https://stackoverflow.com/questions/1211212/how-to-calculate-an-angle-from-three-points
        // atan2(P2.y - P1.y, P2.x - P1.x) - atan2(P3.y - P1.y, P3.x - P1.x)
        return Math.atan2(abc[2].y - abc[0].y, abc[2].x - abc[0].x) - Math.atan2(abc[1].y - abc[0].y, abc[1].x - abc[0].x);

    }

    //public static Vector2 lerp (Vector2 a, Vector2 b, double c) {
    //  
    //  return new Vector2(c*(a.x-b.x)+b.x, c*(a.y-b.y)+b.y);
    //  
    //}

    /*public static Vector2 closestPoint (Vector2[] points, Vector2 point) {

        int leastDistanceIndex = 0;
        double leastDistance = Double.MAX_VALUE;

        for(int i = 0; i < points.length; i++) {
            double dist = distance(points[i], point);
            if(dist < leastDistance) {
                leastDistanceIndex = i;
                leastDistance = dist;
            }
        }

        return points[leastDistanceIndex];

    }*/

    public static int closestPointIndex (Vector2[] points, Vector2 point) {

        int leastDistanceIndex = 0;
        double leastDistance = Double.MAX_VALUE;

        for(int i = 0; i < points.length; i++) {
            double dist = distance(points[i], point);
            if(dist < leastDistance) {
                leastDistanceIndex = i;
                leastDistance = dist;
            }
        }

        return leastDistanceIndex;

    }

    public static double distance (Vector2 a, Vector2 b) {
        return Math.sqrt(Math.pow(Math.abs(a.x-b.x), 2)+Math.pow(Math.abs(a.y-b.y), 2));
    }

}

有用的链接/答案

Snap Point to Line

How to calculate an angle from 3 points