碰撞已完全实施,这里的问题是,当敌人与玩家发生碰撞时,敌人应该弹跳,而不是弹跳,敌人会回到原来的状态。
我尝试了几个应该操纵speedX和X变量的x和y条件。
//碰撞方法
// Checking if there is any collision with player - enemy
public void enemyCollision(Rectangle rect1, ArrayList<Enemy> list) {
Rectangle r = rect1;
int playerX = handler.getPlayer().getX();
int playerY = handler.getPlayer().getY();
for (int i = 0; i < handler.enemyList.size(); i++) {
Enemy enemy = (Enemy) list.get(i);
Rectangle r1 = enemy.getBounds();
// If there is collision. set enemy x and y, set player health -1
if (r.intersects(r1)) {
if (playerX > enemy.x) {
enemy.speedX = enemy.speedX * -1;
}
if (playerX < enemy.x) {
enemy.speedX = enemy.speedX * -1;
}
if (playerY > enemy.y) {
enemy.speedY = enemy.speedY * -1;
}
if (playerY < enemy.y) {
enemy.speedY = enemy.speedY * -1;
}
handler.getPlayer().setHealth(handler.getPlayer().getHealth()-1);
return;
}
}
}
//敌军级的相关代码
// Updating values
@Override
public void tick() {
move(speedX,speedY);
}
// Enemy move
@Override
public void move(float velX, float velY) {
if (x < 0) {
speedX = speedX * -1;
}
if (x > handler.getGame().width - (width+20)) {
speedX = speedX * -1;
}
if (y < 0) {
speedY = speedY * -1;
}
if (y > handler.getGame().height - (height*2)) {
speedY = speedY * -1;
}
x += speedX;
y += speedY;
}
敌人应该与玩家相撞并反弹。