我遇到墙碰撞问题。基本上我希望我的播放器在与块碰撞时停止。 这是我到目前为止所做的:
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;
}
我设置我的代码就像这样,以避免在我与我正在测试的块碰撞时卡住。它有效,但我遇到了很多错误。一个例子是有时候我被卡住了,或者玩家可以通过用水平键按下垂直来穿过块。我在找出适当的算法时遇到了问题。顺便说一下,方向是基于观众的方向而不是玩家的方向。
有人可以与我分享下降的方式吗?感谢。
答案 0 :(得分:1)
对于玩家和墙(块),创建Shapes
(例如Polygon
可以使用)。使用Shape's
方法
public boolean intersects(double x, double y, double w, double h);
public boolean intersects(Rectangle2D r);
或者您可以从Areas
创建Shapes
并使用
public void intersect(Area rhs)