请看这个GIF:
正确检测到碰撞,但这些故障让我很恼火......矩形能够进入另一个矩形。当矩形在 x 轴上碰撞时(并且左右箭头仍然被按下),一个不受影响的人正在移动。有什么想法可以摆脱它们吗?keyPressed、keyReleased、move() 和 checkCollision() 方法:
@Override
public void keyPressed(KeyEvent k) {
int key = k.getKeyCode();
switch (key) {
case KeyEvent.VK_LEFT:
left = true;
game.physic.xVel = 2;
break;
case KeyEvent.VK_RIGHT:
right = true;
game.physic.xVel = 2;
break;
case KeyEvent.VK_SPACE:
//jump
break;
default:
break;
}
}
/*
* game.lvl1.getX()[i] to ablica z współrzędnymi platform
*/
public void move() {
if (left) {
switch (game.currentLevel()) {
case 1:
for (int i = 0; i < game.lvl1.getX().length; i++)
game.lvl1.getX()[i] += game.physic.xVel;
break;
}
} else if (right) {
switch (game.currentLevel()) {
case 1:
for (int i = 0; i < game.lvl1.getX().length; i++)
game.lvl1.getX()[i] -= game.physic.xVel;
break;
}
}
}
public void checkCollision() {
switch (game.currentLevel()) {
case 1:
for (int i = 0; i < game.lvl1.getX().length; i++) {
if (game.man.getBounds().intersects(game.lvl1.getBounds(i))) {
if (game.man.getBounds().getY() < game.lvl1.getBounds(i)
.getY() && !game.man.isOnGround) {
/*
* collision above platform
*/
game.man.setyPos(-2);
game.man.isOnGround = true;
break;
} else if (game.man.getBounds().getY() > game.lvl1
.getBounds(i).getY() && isJumping) {
/*
* collision below
*/
game.man.setyPos(2);
game.man.isOnGround = false;
break;
} else if (game.man.getBounds().getX() < game.lvl1
.getBounds(i).getX() && right) {
/*
* collision from left
*/
game.lvl1.getX()[i] += 2;
right = false;
break;
} else if (game.man.getBounds().getX() > game.lvl1
.getBounds(i).getX() && left) {
/*
* collision from right
*/
game.lvl1.getX()[i] -= 2;
left = false;
break;
}
} else {
game.physic.xVel = 2;
game.man.isOnGround = false;
}
}
}
}
@Override
public void keyReleased(KeyEvent k) {
int key = k.getKeyCode();
switch (key) {
case KeyEvent.VK_LEFT:
left = false;
game.physic.xVel = 0;
break;
case KeyEvent.VK_RIGHT:
right = false;
game.physic.xVel = 0;
break;
case KeyEvent.VK_SPACE:
break;
default:
break;
}
}
从paintComponent 调用paintLevel()。并且paintComponent 是从gameloop 调用的。
private void paintLevel(Graphics2D g2d) {
switch (currentLevel()) {
case 1:
for (int i = 0; i < lvl1.getX().length; i++) {
g2d.draw(lvl1.getBounds(i));
}
break;
}
}