| Java |输入处理程序中的向上和向下总是返回按下

时间:2015-01-02 05:03:17

标签: java

public void tick(){
    int xa = 0;
    int ya = 0;
    if (input.left.isPressed())
        xa--;
    if (input.right.isPressed())
        xa++;
    if (input.up.isPressed())
        ya--;
        System.out.println("Moving up");
    if (input.down.isPressed())
        ya++;   
        System.out.println("Moving Down");      
    if (xa != 0 || ya != 0){
        move(xa, ya);
        isMoving = true;
    }
    else
        isMoving = false;
}

当我运行游戏时,水平方向工作完美,但程序不断输出"向上移动"和"向下移动"

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class InputHandeler implements KeyListener {

    public Key up = new Key();
    public Key down = new Key();
    public Key left = new Key();
    public Key right = new Key();

    public InputHandeler(MainGame game){
        game.addKeyListener(this);
    }

    public class Key{
        public boolean pressed = false;

        public boolean isPressed(){
            return pressed;
        }

        public void toggle (boolean isPressed){
            pressed = isPressed;
        }
    }


    public void keyPressed(KeyEvent e) {
        toggleKey(e.getKeyCode(), true);
    }

    public void keyReleased(KeyEvent e) {
        toggleKey(e.getKeyCode(), false);
    }

    public void keyTyped(KeyEvent arg0) {

    }

    public void toggleKey(int keyCode, boolean isPressed){
        if (keyCode == KeyEvent.VK_W || keyCode == KeyEvent.VK_UP)
            up.toggle(isPressed);
        if (keyCode == KeyEvent.VK_S || keyCode == KeyEvent.VK_DOWN)
            down.toggle(isPressed);
        if (keyCode == KeyEvent.VK_A || keyCode == KeyEvent.VK_LEFT)
            left.toggle(isPressed);
        if (keyCode == KeyEvent.VK_D || keyCode == KeyEvent.VK_RIGHT)
            right.toggle(isPressed);
    }
}

感谢任何帮助。

这是移动方法

 public void move(int xa, int ya){
    if (xa != 0 && ya != 0){
        move(xa, 0);
        move(0, ya);
        numSteps--;
        return; 
    }
    numSteps++; 
    if (hasCollided(xa, ya) != true){
        if(ya < 0)
            movingDir = 0;
        if(ya > 0)
            movingDir = 1;
        if(xa < 0)
            movingDir = 2;
        if(xa > 0)
            movingDir = 3;          
        x += xa * speed;
        y += ya * speed;
    }
}

我可以侧身而不是上下移动,我不知道为什么

0 个答案:

没有答案