所以在我的小侧滚动Java游戏中,我试图让我的角色与墙壁发生碰撞。我使用键绑定而不是键侦听器,因为它经常引起聚焦问题。这是我遇到问题的代码:
Action moveleft = new AbstractAction(){
public void actionPerformed(ActionEvent e)
{
if (moving==true&&offsetX!=2){
offsetX=offsetX+2;
}
}
};
问题在于,当按下某个键以使角色移动时,在执行操作的方法中,它不会重新检查条件语句,该条件语句确定在按住键时移动是真还是假。这导致角色无限期地穿过所有墙壁直到钥匙被释放。
那为什么呢?我该怎么做才能解决这个问题?如果我的程序需要更多代码,我可以提供!谢谢!
这是我的小组类的简略版本,其中基本上发生了所有碰撞:
public class Panel extends JPanel implements ActionListener
{
public static boolean moving=true;
Player p1;
public InputMap inputmap;
public ActionMap actionmap;
ArrayList<Level> Levels;
Level level1;
protected static int offsetX=0;
protected static int offsetY=0;
public Panel() {
inputmap = getInputMap(WHEN_IN_FOCUSED_WINDOW);
inputmap.put(KeyStroke.getKeyStroke("D"), "startright");
inputmap.put(KeyStroke.getKeyStroke("A"), "startleft");
inputmap.put(KeyStroke.getKeyStroke("released D"), "stop");
inputmap.put(KeyStroke.getKeyStroke("released A"), "stop");
actionmap = getActionMap();
actionmap.put("startright", moveright);
actionmap.put("startleft", moveleft);
actionmap.put("startup", moveup);
actionmap.put("startdown", movedown);
actionmap.put("stop", stop);
}
//The game's main game loop
@Override
public void actionPerformed(ActionEvent evt) {
if (!running){
startGame();
}
gameUpdate();
repaint();
}
//Updates the game every iteration
private void gameUpdate() {
p1.update();
for (int i = 0; i < Levels.size(); i++) {
collide(p1, level1.Blocks.get(i));
}
}
Action moveright = new AbstractAction()
{
public void actionPerformed(ActionEvent e)
{
//p1.setRight(e);
if (moving==true&&offsetX!=-2){
offsetX=offsetX-2;
}
}
};
Action moveleft = new AbstractAction()
{
public void actionPerformed(ActionEvent e)
{
//p1.setLeft(e);
if (moving==true&&offsetX!=2){
offsetX=offsetX+2;
}
}
};
Action moveup = new AbstractAction()
{
public void actionPerformed(ActionEvent e)
{
//p1.setUp(e);
if (moving==true&&offsetY!=-1){
offsetY=offsetY-1;
}
}
};
Action movedown = new AbstractAction()
{
public void actionPerformed(ActionEvent e)
{
//p1.setDown(e);
if (moving==true&&offsetY!=1){
offsetY=offsetY+1;
}
}
};
Action stop = new AbstractAction()
{
public void actionPerformed(ActionEvent e)
{
//p1.stop(e);
offsetX=0;
offsetY=0;
}
};
public void collide(Player p, Block b) {
if (Math.abs(p.minX) < Math.abs(b.maxX)) {
moving=false;
}
else {
//moving=true;
}
}
}
这基本上都是涉及碰撞的一切。我真的只是想知道为什么即使在moving == false
时actionPerformed方法仍然会增加偏移量。