有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java算法,用于从用户中选择一个多边形

我想不出一个合适的算法来检测用户是否选择了多边形。 这是我的例子: enter image description here

  • 如果用户单击多边形1,则选择多边形1
  • 如果用户单击多边形2,则选择多边形2
  • 如果用户点击多边形三的左侧(我不确定这是什么最好的直觉反应,所以实际是什么都没有发生)
  • 如果用户单击多边形的右侧,则选择“三”
  • 用户点击五次或四次将选择五次或四次

这是我对这些要求的实现:

// polygons - a List which contains all Polygons from a scene
Point position = input.getMouse();
List<ChangeablePolygon> selectedPolygons = new ArrayList<>();
for (ChangeablePolygon polygon : polygons) {
    polygon.setSelected(false);
    if (polygon.intersects(position))
        selectedPolygons.add(polygon);
}

if (selectedPolygons.size() == 1) {
    selectedPolygons.get(0).setSelected(true);
} else if (selectedPolygons.size() == 2) {
    ChangeablePolygon one = selectedPolygons.get(0);
    ChangeablePolygon two = selectedPolygons.get(1);
    if (Maths.isPolygonInPolygon(one, two)) {
        two.setSelected(true);
    } else if (Maths.isPolygonInPolygon(two, one)) {
        one.setSelected(true);
    } else if (one.getArea() < two.getArea()) {
        two.setSelected(true);
    } else {
        one.setSelected(true);
    }
}

/**
 * Polygon#intersects(Point):boolean
 *
 * true - if the Point is in the Polygon
 * false - otherwise 
 *
 * Polygon#getArea():double 
 * Returns the size auf the area from the Polygon 
 *
 * Maths#isPolygonInPolygon(Polygon polygon,Polygon inside):boolean
 *
 * true - if all Points from Polygon 'inside' are inside the Polygon 'Polygon'
 * false - otherwise
 */

但不幸的是,它在这个测试用例中失败了。因为如果选择一个多边形,我选择了三个多边形,而我的算法无法处理这种情况

enter image description here

当然,我可以简单地将我的“两个”场景扩展到如下内容:

ChangeablePolygon one = selectedPolygons.get(0);
ChangeablePolygon two = selectedPolygons.get(1);
ChangeablePolygon three = selectedPolygons.get(2);

if (Maths.isPolygonInPolygon(one, two) && Maths.isPolygonInPolygon(two, three)) {
    three.setSelected(true);
} else if (Maths.isPolygonInPolygon(two, one)) {
    one.setSelected(true);
} else if (Maths.isPolygonInPolygon(one, two)) {
    two.setSelected(true);
}

但必须有更好的解决方案。我在寻找一种循环,如何处理更多的“堆叠”多边形,而不必为每个多边形添加一个if-else情况。我没想到什么有用的

我应该提到的是,我使用的发动机没有加油。不幸的是,我不能使用图形解决方案。有没有唯一可能的数学方法来计算?效率不那么重要。这是一张直接来自引擎的未编辑图像

enter image description here


共 (0) 个答案