我正在创建一个游戏,pacman专门作为我的课程的一部分,当涉及到使用矩形进行碰撞检测时,我遇到了问题。
我遇到的问题是,即使在屏幕上,很清楚地看到字符没有碰撞,检查交叉口几乎总是返回true。下面的输出解释了我的意思:
Pacman详细信息:X 17.0 y 16.0 Inky details: X 22.0 y 13.0调用相交后碰撞():true Pacman details: X18.0 y 16.0 Inky details: X23.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;
}在这一点上,我已经几乎没有关于如何解决这个问题的想法,所以,任何建议,你们可以给会非常感谢!
发布于 2011-04-09 01:54:23
假设getX()和getY()返回矩形的左上角坐标的点,那么这些是每个调用的矩形的边界:
Pacman详细信息:X 17.0 y 16.0 Inky details: X22.0 y 13.0调用intersects()后碰撞: true
帕克曼矩形将是其左上角坐标加22在每个方向,给你一个矩形与右下角(39.0, 38.0),最明确的交叉,如果他的右上角是(22.0, 13.0),左下角是(44.0, 35.0)。
在我看来就是这样。你的意思是22.0是Pacman和Inky矩形的边界(像素还是正方形)?如果这些假设是正确的,那么Inky的左下角(22.0, 35.0)实际上是完全位于Pacman内部,这可能不是您想要的。问题可能有很多,如果不知道更多的代码和矩形的确切含义,就很难说出它可能是什么。:D
https://stackoverflow.com/questions/5602239
复制相似问题