Java:帮助确定两个矩形之间的碰撞

时间:2011-04-09 01:14:58

标签: java collision-detection rectangles

我正在创建一个游戏,pacman专门作为我课程的一部分而且我在使用矩形进行碰撞检测时遇到了问题。

我遇到的问题是即使在屏幕上很清楚地看到角色没有碰撞检查交叉点实际上总是返回true。下面的输出解释了我的意思:

  

Pacman详情:x 17.0 y 16.0   Inky细节:x 22.0 y 13.0   调用intersects()后的碰撞:true   Pacman细节:x 18.0 y 16.0   Inky细节:x 23.0 y 13.0   调用intersects()后的碰撞:true

我将矩形设置如下:

public Rectangle pacmanBounds(){
    return new Rectangle(pacRow, pacColumn, 22, 22);
}
public Rectangle ghostBounds(){
    return new Rectangle(ghostRow, ghostColumn, 22, 22);
}

高度和宽度已经过硬编码以用于测试目的,但这些是实际的图像尺寸。

每次重新绘制JPanel时,我都会按照以下方式检查碰撞:

public boolean checkCollision(){
    Rectangle pacmanBounds = pacman.pacmanBounds();
    //currently commented out for testing
    /*if(pacmanBounds.intersects(inky.ghostBounds()) || pacmanBounds.intersects(blinky.ghostBounds())
            || pacmanBounds.intersects(pinky.ghostBounds()) || pacmanBounds.intersects(clyde.ghostBounds())){
        System.out.println("Oh no!");
        return true;
    }*/

    System.out.println("Pacman details: x " + pacmanBounds.getX() + " y " + pacmanBounds.getY() + " ");
    System.out.println("Inky details: x " + inky.ghostBounds().getX() + " y " + inky.ghostBounds().getY());
    System.out.println("Collision after calling intersects(): " + pacmanBounds.intersects(inky.ghostBounds()));
    return false;
}

目前我几乎没有关于如何解决这个问题的想法,所以你们给予的任何建议都会非常感激!

1 个答案:

答案 0 :(得分:1)

假设getX()getY()返回矩形左上角坐标的点,那么这些将是每次调用的矩形边界:

  

Pacman细节:x 17.0 y 16.0 Inky细节:x 22.0 y 13.0调用intersects后的碰撞():true

Pacman矩形将是它的左上角坐标加上每个方向的22个,给你一个右下角(39.0, 38.0)的矩形,如果他的右上角是{{1,则最明确地与Inky相交左下角是(22.0, 13.0)

这就是我的样子。你的意思是22.0是像素或正方形的Pacman和Inky矩形的界限吗?如果这些假设是正确的,那么Inky的左下角(44.0, 35.0)就完全位于Pacman内部,这可能不是你想要的。问题可能是很多事情,如果不知道看到更多的代码并知道矩形的确切含义,很难说它可能是什么。 :d

相关问题