独特的乒乓球拍运动,带键装

时间:2017-09-16 17:26:05

标签: java

所以我正在进行一场乒乓球比赛,我正在处理输入。目前屏幕上有两个拨片,左边的一个ID为1,另一个的Id为2.进行键绑定时,我编写了以下代码;

public class Input implements Constants
{

    private ActionMap am;
    private InputMap im;

    //--------ACTIONS--------//
    private final String MOVE_UP ="moveUp";
    private final String MOVE_UP_RELEASED ="moveUpReleased";
    private final String MOVE_DOWN ="moveDown";
    private final String MOVE_DOWN_RELEASED ="moveDownReleased";
    //--------ACTIONS--------//

    private GamePanel gp;

    public Input(Core c, GamePanel gp)
    {
        this.gp = gp;
        im = c.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
        am = c.getActionMap();

        addStroke(KeyEvent.VK_W, false, MOVE_UP, 1);
        addStroke(KeyEvent.VK_W, true, MOVE_UP_RELEASED, 1);

        addStroke(KeyEvent.VK_S, false, MOVE_DOWN, 1);
        addStroke(KeyEvent.VK_S, true, MOVE_DOWN_RELEASED, 1);

        addStroke(KeyEvent.VK_UP, false, MOVE_UP, 2);
        addStroke(KeyEvent.VK_UP, true, MOVE_UP_RELEASED, 2);

        addStroke(KeyEvent.VK_DOWN, false, MOVE_DOWN, 2);
        addStroke(KeyEvent.VK_DOWN, true, MOVE_DOWN_RELEASED, 2);

    }

    public void addStroke(int key, boolean released, String action, int playerId)
    {
        im.put(KeyStroke.getKeyStroke(key, 0, released), action);
        if(playerId == 0) //If a player Id is not provided, key command does not involve player. 
            am.put(action,  new Action(action));
        else
            am.put(action,  new Action(action, playerId));
    }

    private class Action extends AbstractAction
    {

        private static final long serialVersionUID = 1L;
        private String action;
        private int playerId;

        public Action(String action)
        {
            this.action = action;
        }

        public Action(String action, int playerId)
        {
            this.action = action;
        }

        @Override
        public void actionPerformed(ActionEvent e) 
        {
            switch(action)
            {
            case MOVE_UP:
                gp.getPaddle(playerId).setVel(-PADDLE_VEL);
                break;
            case MOVE_UP_RELEASED:
                gp.getPaddle(playerId).setVel(0);
                break;
            case MOVE_DOWN:
                gp.getPaddle(playerId).setVel(PADDLE_VEL);
                break;
            case MOVE_DOWN_RELEASED:
                gp.getPaddle(playerId).setVel(0);
                break;
            }
        }

    }

}

此代码的问题在于,只有按下W或S或UP或DOWN,它才会移动Id为2的球拍。

问题纯粹是在这里,因为如果我删除ID为2的任何东西,它将成功移动桨1.如果有人可以帮我找出为什么这只是移动一个桨我会非常感激它!

0 个答案:

没有答案