首页 > 解决方案 > 与 intersectLinePolygon 相交的多边形和线行为不正常

问题描述

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

现在,我决定使用 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):

photoshop图片链接

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

我想我要么没有正确使用该功能,要么我犯了一些明显的错误。或者这是功能应该如何反应?我真的不知道。谢谢你的帮助 :)

标签: javamathvectorlibgdxcollision

解决方案


好的,显然我使用了错误的方法。intersectSegmentPolygon 按预期工作。我的坏¯_(ツ)_/¯。


推荐阅读