我为这个正在进行的简单游戏制作了这个矩形碰撞系统,但是它运行不正常。它仅在玩家的左下角像素与对象碰撞时才会记录碰撞,我无法弄清楚原因。提前感谢您的帮助。
public static boolean collision(int playerX, int playerY, int playerWidth, int playerHeight,
int obstacleX, int obstacleY, int obstacleWidth, int obstacleHeight){
if (coordinateWithinRect(playerX, playerY, obstacleX,
obstacleY, obstacleWidth, obstacleHeight)) {
return true;
} else if (coordinateWithinRect(playerX - playerWidth,
playerY, obstacleX, obstacleY, obstacleWidth,
obstacleHeight)) {
return true;
} else if (coordinateWithinRect(playerX - playerWidth,
playerY + playerHeight, obstacleX, obstacleY,
obstacleWidth, obstacleHeight)) {
return true;
} else if (coordinateWithinRect(playerX, playerY
+ playerHeight, obstacleX, obstacleY, obstacleWidth,
obstacleHeight)) {
return true;
} else {
return false;
}
}
private static boolean coordinateWithinRect(int xCoord, int yCoord, int xRect, int yRect, int width, int height) {
if (xCoord > xRect && xCoord < (xRect + width) && yCoord < yRect && yCoord > (yRect - height)) {
return true;
} else {
return false;
}
}
答案 0 :(得分:1)
在你的功能coordinateWithinRect
中,您可以为障碍物指定宽度和高度,但不能为您的玩家指定。这是故意的吗,我的意思是你的玩家没有任何尺寸,或者他们被认为不重要?
无论如何,根据你对碰撞的定义的总体思路来判断,我猜玩家被认为是在障碍物的矩形内部与障碍碰撞,对吧? 所以,你应该检查是否
playerX
位于obstacleX-obstacleWidth/2
内,obstacleX+obstacleWidth/2
位于playerY
同时位于obstacleY-obstacleHeight/2
和obstacleY+obstacleHeight/2
内。你的功能应该是:
private static boolean coordinateWithinRect(int xPunkt, int yPunkt, int xRect, int yRect, int bredd, int höjd) {
if (playerX > (obstacleX-obstacleWidth/2) && playerX < (obstacleX+obstacleWidth/2) && playerY > (obstacleY-obstacleHeight/2) && playerY < (obstacleY+obstacleHeight/2)) {
return true;
} else {
return false;
}
}
您不进行这些检查以确定您在此处有问题或者我遗失了什么?
答案 1 :(得分:0)
我设法自己修复了代码,我会解释这个问题并在下面修复,因为任何人都有相同或类似的问题。
问题在于我使用了常规二维坐标系的想法,其中X向右增加,Y增加了向上。在java中它是相反的。固定代码如下所示:
public static boolean collision(int playerX, int playerY, int playerWidth, int playerHeight,
int obstacleX, int obstacleY, int obstacleWidth, int obstacleHeight){
if (coordinateWithinRect(playerX, playerY, obstacleX,
obstacleY, obstacleWidth, obstacleHeight)) {
return true;
} else if (coordinateWithinRect(playerX + playerWidth,
playerY, obstacleX, obstacleY, obstacleWidth,
obstacleHeight)) {
return true;
} else if (coordinateWithinRect(playerX + playerWidth,
playerY - playerHeight, obstacleX, obstacleY,
obstacleWidth, obstacleHeight)) {
return true;
} else if (coordinateWithinRect(playerX, playerY
- playerHeight, obstacleX, obstacleY, obstacleWidth,
obstacleHeight)) {
return true;
} else {
return false;
}
}
private static boolean coordinateWithinRect(int xCoord, int yCoord, int xRect, int yRect, int width, int height) {
if (xCoord > xRect && xCoord < (xRect + width) && yCoord < yRect && yCoord > (yRect - height)) {
return true;
} else {
return false;
}
}