【发布时间】: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