【问题标题】:Java: Help determining a collision between two rectanglesJava:帮助确定两个矩形之间的碰撞
【发布时间】:2011-04-09 09:54:23
【问题描述】:

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

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

吃豆人详细信息:x 17.0 y 16.0 墨色细节:x 22.0 y 13.0 调用 intersects() 后发生碰撞:true Pacman 详细信息:x 18.0 y 16.0 墨色细节: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;
}

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

【问题讨论】:

  • 很明显这两个矩形相交:{(17, 16), (39, 38)} 和 {(22, 13), (44, 35)}。我想问题是为什么图像看起来不像相交?是否有大的透明边框?
  • 感谢您的评论 rlibby,您对交叉点的看法是正确的,我想我完全忘记了矩形是如何工作的!我现在已经缩小了矩形的大小并且它正在工作:)

标签: java collision-detection rectangles


【解决方案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

【讨论】:

  • 感谢您的评论,是的,您是对的,我想我在自己的代码中迷失了(忘记了矩形是如何工作的)!添加 22 太大了,我现在把它缩小了,它工作得很好,或者尽可能接近凌晨 3 点! :)
  • @tfstorm 很高兴为您提供帮助!欢迎来到 Stackoverflow! :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-01
  • 2018-10-09
相关资源
最近更新 更多