この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;
}
}
paintLevel()はpaintComponentから呼び出されます。そして、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;
}
}