1

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

我遇到的问题是,即使在屏幕上可以清楚地看到字符没有碰撞,检查交叉点实际上总是返回 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;
}

在这个时间点上,我几乎没有关于如何解决这个问题的想法,所以你们可以提供的任何建议将不胜感激!

4

1 回答 1

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)如果他的右上角是(22.0, 13.0)并且左下角是,它肯定会与 Inky 相交(44.0, 35.0)

这就是我的样子。你的意思是 22.0 是 Pacman 和 Inky 矩形的边界,以像素为单位还是以正方形为单位?如果这些假设是正确的,那么 Inky 的左下角(22.0, 35.0)实际上完全位于 Pacman 内部,这可能不是您想要的。问题可能是多方面的,如果不知道看到更多代码并知道矩形的确切含义,很难说它可能是什么。:D

于 2011-04-09T01:54:23.143 回答