我遇到了墙壁碰撞的问题。基本上,我希望我的播放器在与块碰撞时停止。这是我到目前为止所做的:
Keylistener 设置:
addKeyListener(new KeyAdapter(){
public void keyPressed(KeyEvent e){
if(e.getKeyCode() == KeyEvent.VK_A){
pressL = true;
}
if(e.getKeyCode() == KeyEvent.VK_D){
pressR = true;
}
if(e.getKeyCode() == KeyEvent.VK_W){
pressU = true;
}
if(e.getKeyCode() == KeyEvent.VK_S){
pressD = true;
}
}
public void keyReleased(KeyEvent e){
if(e.getKeyCode() == KeyEvent.VK_A){
pressL = false;
}
if(e.getKeyCode() == KeyEvent.VK_D){
pressR = false;
}
if(e.getKeyCode() == KeyEvent.VK_W){
pressU = false;
}
if(e.getKeyCode() == KeyEvent.VK_S){
pressD = false;
}
}
public void keyTyped(KeyEvent e){
}
});
玩家移动:
public void playerMovement(){
player.horizontalMovement(0);
player.verticalMovement(0)
map.horizontalMovement(0);
map.verticalMovement(0);
if(pressR && !pressL && !pressU && !pressD){
if(!east){
toggleRight();
}
if(collision("east"))
east = true;
}
if(pressL && !pressR && !pressD && !pressU){
if(!west)
toggleLeft();
if(collision("west"))
west = true;
}
if(pressD && !pressU && !pressR && !pressL){
if(!south)
toggleDown();
if(collision("south"))
south = true;
}
if(pressU && !pressD && !pressL && !pressR){
if(!north)
toggleUp();
if(collision("north"))
north = true;
}
}
这里是碰撞测试的地方:
public boolean collision(String loc){
Rectangle pR = player.getBound();
Rectangle pM = map.getBound(0, 0);
if(loc.equals("east")){
if(pR.equals(pM)){
if(west)
return false;
if(!west)
return true;
} west = false; south = false;north = false;
}
if(loc.equals("west"))
if(pR.intersects(pM)){
if(east)
return false;
if(!east)
return true;
} east = false; south = false;north = false;
}
if(loc.equals("south")){
if(pR.intersects(pM)){
if(north)
return false;
if(!north)
return true;
} north = false; west = false;east = false;
}
if(loc.equals("north")){
if(pR.intersects(pM)){
if(south)
return false;
if(!south)
return true;
} south = false; west = false;east = false;
}
return false;
}
我像这样设置我的代码,以避免在与我正在测试的块发生碰撞时被卡住。它有效,但我遇到了很多错误。一个例子是有时我被卡住了,或者玩家可以通过使用水平键按下垂直来穿过块。我在为此找出正确的算法时遇到问题。顺便说一句,方向是基于观看者的方向而不是玩家的方向。
有人可以与我分享一种下降方式吗?谢谢。