与intersectLinePolygon相交的多边形和线的行为不正确

时间:2018-07-30 16:32:20

标签: java math vector libgdx collision

我正在尝试检测光标周围的小矩形和“连接器”之间的碰撞,“连接器”基本上只是两点之间的线。

现在,我决定使用Intersector.intersectLinePolygon(p1,p2,polygon)方法来执行此操作,但是在运行代码时。每当矩形的X或Y点与线的边界框处于同一范围内时,它都会检测到碰撞,而我实在无法绕开它。理想的结果是仅在矩形实际接触到直线时才报告碰撞。

        Vector3 worldPos = cam.unproject(new Vector3(mouseX, mouseY, 0));

        Rectangle rect = new Rectangle(worldPos.x-4, worldPos.y-4, 8, 8);

        Boolean connectorIntersected = false;   
        for (int i = 0; i < nodeConnectorHandler.getAllConnectors().size(); i++) {
            //Getting two points that make the connector line
            Node n1 = nodeConnectorHandler.getAllConnectors().get(i).getFrom();
            Node n2 = nodeConnectorHandler.getAllConnectors().get(i).getTo();

            float x1 = n1.getCX();
            float y1 = n1.getCY();
            float x2 = n2.getCX();
            float y2 = n2.getCY();

            //Making a polygon out of rect
            Polygon p = new Polygon(new float[] {
                    rect.getX(),
                    rect.getY(),
                    (rect.getX()+8f),
                    rect.getY(),                                                                                                            
                    (rect.getX()+8f),
                    (rect.getY()+8f),
                    rect.getX(),
                    (rect.getY()+8f)
            });

            //Checking if the line intersects the polygon (representing the rectangle around the cursor)

            if (Intersector.intersectLinePolygon(new Vector2(x1,y1), new Vector2(x2,y2), p)) 
            {   
                selectedIndex =  nodeConnectorHandler.getAllConnectors().get(i).getID();
                System.out.println("ConnectorIntersected!");
                connectorIntersected = true;
            }                   
            break
         }

每次矩形在这些区域中时,代码都会报告冲突(以黄色,大约aprox表示):

photoshopped image link

这两个点之间的红线是“连接器” 光标在该行的正下方。它报告了在整个游戏世界的黄色区域发生的碰撞。

我想我要么没有正确使用函数,要么我犯了一些明显的错误。还是这应该如何反应?我真的不知道感谢您的帮助:)

1 个答案:

答案 0 :(得分:0)

好吧,显然我使用了错误的方法。 intersectSegmentPolygon可以正常工作。我的坏¯_(ツ)_ /¯。