首页 > 解决方案 > java中的碰撞检测问题。intersectsWith 方法总是返回 true

问题描述

我目前正在开发一款游戏,但我的碰撞检测存在问题:

这些是我实现的方法:

public boolean intersectsWith(GameObject other) {   
    if(getTopRightPoint(this)[1] < getBottomLeftPoint(other)[1]
            || getBottomLeftPoint(this)[1] > getTopRightPoint(other)[1]) {
        return false;
    }
    if(getTopRightPoint(this)[0] < getBottomLeftPoint(other)[0]
            || getBottomLeftPoint(this)[0] > getTopRightPoint(other)[0]) {
        return false;
    }

    System.out.println("COLLISION BETWEEN " + this.getClass().getSimpleName() + " and "+ other.getClass().getSimpleName());
    return true;

}

private double[] getBottomLeftPoint(GameObject gameObject){
    return new double[] {gameObject.actualPosition[0], gameObject.actualPosition[1]};
}

private double[] getTopRightPoint(GameObject gameObject) {
    return new double[] {gameObject.actualPosition[0] + gameObject.getCurrentSprite().getWidth(), gameObject.actualPosition[1] + gameObject.getCurrentSprite().getHeight()};
}

然后,每当时间推进时,我都会使用以下方法检查碰撞:

    gameObjects.stream().forEach(o1 -> gameObjects.stream().forEach(o2 -> {
        if (o1 != o2 && o1.intersectsWith(o2)) {
          o1.collision(o2);
        }
      }));

这应该可以,但它会继续打印该行

 System.out.println("COLLISION BETWEEN " + this.getClass().getSimpleName() + " and "+ other.getClass().getSimpleName());

这告诉我,即使没有,也总是有碰撞。

我怎样才能解决这个问题?

标签: javacollision-detection

解决方案


如果您的坐标是 Bottom X Left,那么您的实际 getTopRightPoint 实现将返回 Bottom + Width;左 + 高度,这实际上是在对象边界之外。

正确的是:底部-高度=顶部;左 + 宽度 = 右

private double[] getTopRightPoint(GameObject gameObject) {
    return new double[] {gameObject.actualPosition[0] - gameObject.getCurrentSprite().getHeight(), gameObject.actualPosition[1] + gameObject.getCurrentSprite().getWidth()};
}

PS:您还向底部添加了宽度,该宽度必须为高度(以及向左的高度)


推荐阅读