【问题标题】:Can't detect collision with Polygon无法检测与多边形的碰撞
【发布时间】:2022-01-22 19:28:56
【问题描述】:

一些背景——这是一个小行星游戏

我正在尝试检测圆和 Polygon 对象之间的碰撞,因此我将 Polygon.contains() 与圆的坐标一起使用。 但由于某些未知的原因,它有时才实际检测到碰撞: 当第一颗流星(多边形)出现时,我会尝试射击它(子弹是圆圈),它可能检测到它,但不确定第二颗流星也是如此,依此类推——换句话说检测并不总是有效。

代码:

 public void run() {
        super.run();
        while (true){
            decreaseArr(this.shapes[0].xpoints,1);
                if (!Bullet.bulletList.isEmpty()){
                    for (int i = 0; i< Bullet.bulletList.size() ; i++){
                            Bullet currentBullet= Bullet.bulletList.get(i);
                            if (this.shapes[0].contains(currentBullet.x, currentBullet.y)){
                                System.out.println(meteorList.indexOf(this));
                                System.out.println("HIT!");
                                Bullet.bulletList.remove(currentBullet); //Delete bullet from screen
                                meteorList.remove(this); //Delete from screen
                                breakFlag=true;
                                System.out.println(Meteor.meteorList);
                            }
                    }
                    if (breakFlag)
                        break;
                }
            try {
                TimeUnit.MILLISECONDS.sleep(meteorVelocity);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

(这是 Meteor 类中的 run 方法,因此每个流星都有一个形状数组(现在它只有一个形状,但稍后我会添加更多形状))

编辑: Some video footage(抱歉没早点编辑,刚回家:))

编辑 2:

重要提示: 每次我运行游戏时,我不会能够像以前一样摧毁相同的流星 - 每次我得到不同的结果

【问题讨论】:

  • 我没有看到Polygon 实例的列表,也没有看到对Polygon intersects 方法的调用。
  • 你的子弹移动得足够快,可能会“穿过”流星吗?
  • Edit 添加一个minimal reproducible example 就像this answer,顺便说一下,这是关于复杂(Java-2D)形状的碰撞检测。事实上,首先运行该代码以检查它是否符合您的预期,然后尝试将这些方法调整到您自己的代码中。如果 那个 失败,请在此处添加您的最佳尝试作为 MRE。
  • 是的,我在课堂上写了这篇文章,无法拍照只是正要编辑它:)
  • @VGR 子弹的速度远不及“通过”(检查)

标签: java list swing collision-detection polygon


【解决方案1】:

在对 Polygon 进行任何更改后,必须调用 invalidate()

【讨论】:

  • 添加为评论
猜你喜欢
  • 2012-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-24
  • 1970-01-01
  • 2013-03-09
  • 1970-01-01
相关资源
最近更新 更多