Libgdx测试线是否与矩形相交

时间:2016-05-06 21:38:46

标签: java android libgdx 2d

有没有办法可以测试Rectangle对象是否与线条发生碰撞?谢谢!

编辑:

public boolean overlapsLineNodes(Vector2 point1, Vector2 point2) {

    boolean collide = false;

    MapObjects mapObjects = play.getWorld().level.getCurrentLevel().getLayers().get("collidable").getObjects();

    Tools.shapeRenderer.setAutoShapeType(true);
    Tools.shapeRenderer.setProjectionMatrix(play.getCamera().combined);
    Tools.shapeRenderer.begin();

    for (RectangleMapObject rectangleObject : mapObjects.getByType(RectangleMapObject.class)) {

        rectangle.setX(rectangleObject.getRectangle().x * 1/64f);
        rectangle.setY(rectangleObject.getRectangle().y * 1/64f);
        rectangle.setWidth(rectangleObject.getRectangle().width * 1/64f);
        rectangle.setHeight(rectangleObject.getRectangle().height * 1/64f);

        float   x1 = rectangle.x, y1 = rectangle.y + rectangle.height,
                x2 = rectangle.x + rectangle.width, y2 = rectangle.y + rectangle.height,
                x3 = rectangle.x + rectangle.width, y3 = rectangle.y,
                x4 = rectangle.x, y4 = rectangle.y;

        Vector2 start = point1, end = point2;

        float[] floatArray = new float[]{x1, y1, x2, y2, x3, y3, x4, y4};
        polygon.setVertices(floatArray);

        if (Intersector.intersectLinePolygon(start, end, polygon)) {
            Tools.shapeRenderer.setColor(Color.GREEN);
            collide = true;
        }

        Tools.shapeRenderer.line(point1.x, point1.y, point2.x, point2.y);

        Tools.shapeRenderer.rect(rectangle.x, rectangle.y, rectangle.width, rectangle.height);

        Tools.shapeRenderer.setColor(Color.WHITE);


    }

我这样做,但似乎没有给我正确的结果。我以白色渲染所有的rectanglemapobjects,如果一个与该线相撞,那么我将它呈现为绿色。它随机呈现一些绿色,我无法弄清楚原因。

3 个答案:

答案 0 :(得分:2)

问题是intersectLinePolygon是错误的方法!我应该一直在使用intersectSegmentPolygon。

答案 1 :(得分:0)

计算线与定义矩形一条边的直线的交点,确定交点是否位于边的端点之间。用相反的边缘重复。如果你得到“是”,它们会交叉。

您不需要测试所有4条边;只是两个相对的边缘。

如果矩形边与轴平行... [x1,y1] - [x2,y1] - [x2,y2] - [x1,y2] ......你所讨论的线是y = m * x + b,然后这变得简单:

ya = m*x1 + b;
yb = m*x2 + b;

collision = ((ya < y1) ^ (ya < y2))  ||  ((yb < y1) ^ (yb < y2));

或者,如果您订购“ya&lt; yb”,您可以更准确地了解是否只是碰到一个角落被认为是碰撞:

collision = ((ya <= y1) && (y1 <= yb)) ||  ((ya <= y2) && (y2 <= yb));

答案 2 :(得分:0)

假设您知道行的startend点以及矩形的vertices(您必须知道这是诚实的:))您可以使用Intersector的{{1}方法就像

intersectLinePolygon()

如果您在 //definition of variables - of course you can keep your x... y... in float[] array float x1 = 0, x2 = 0, x3 = 0, x4 = 0, y1 = 0, y2 = 0, y3 = 0, y4 = 0; Vector2 start = null, end = null; //... //updateing vertices and line start/end points //... Intersector.intersectLinePolygon(start, end, new Polygon(new float[]{x1, y1, x2, y2, x3, y3, x4, y4})); 方法中使用此方法,那么每次创建render()实例都不合适 - 最好将一个实例保留在某处

new Polygon()

然后在碰撞检查之前用顶点更新它

    Polygon p = new Polygon();