2D游戏“跳跃”

时间:2013-12-11 17:11:18

标签: java swing jframe

我一直在使用java中的一个非常简单的2D游戏,可能最终将它用作flash游戏或其他什么时候完成,我很早就意识到我无法“跳”到“字符“由键移动(也就是此代码中的绿色框):

import javax.swing.*;
import java.awt.Graphics;
import javax.swing.AbstractAction;
import javax.swing.Action;
import java.awt.event.ActionEvent;
import java.awt.Color;

public class SquareGame extends JPanel{
    static final int SIZE = 400;
    static int x = SIZE / 2, width = 25, y = (SIZE / 2) - width, height = 25;
    public static SquareGame m = new SquareGame();
    public static void main(String[] args){
        final JFrame frame = new JFrame();
        frame.add(m);
        frame.setTitle("Square Game");
        frame.setSize(SIZE, SIZE);
        frame.setResizable(false);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);

        Action actionRight = new AbstractAction(){
            public void actionPerformed(ActionEvent actionRightEvent){
                if(x < (SIZE - width)){
                    x += (width / 5);
                }
            }
        };

        Action actionLeft = new AbstractAction(){
            public void actionPerformed(ActionEvent actionLeftEvent){
                if(x > 0){
                    x -= (width / 5);
                }
            }
        };

        Action actionUp = new AbstractAction(){
            public void actionPerformed(ActionEvent actionUpEvent){
                if(y > ((SIZE / 2) - (height * 2))){
                    y -= (height / 5);
                }
            }
        };

        Action actionRelUp = new AbstractAction(){
            public void actionPerformed(ActionEvent actionUpEvent){
                if(y < (SIZE / 2) - height){
                    y += (height / 5);
                }
            }
        };

        KeyStroke keyRight = KeyStroke.getKeyStroke("RIGHT");
        KeyStroke keyLeft = KeyStroke.getKeyStroke("LEFT");
        KeyStroke keyUp = KeyStroke.getKeyStroke("SPACE");
        KeyStroke relUp = KeyStroke.getKeyStroke("released SPACE");

        InputMap inputMap = m.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
        inputMap.put(keyRight, "RIGHT");
        inputMap.put(keyLeft, "LEFT");
        inputMap.put(keyUp, "SPACE");
        inputMap.put(relUp, "released SPACE");

        m.getActionMap().put("RIGHT", actionRight);
        m.getActionMap().put("LEFT", actionLeft);
        m.getActionMap().put("SPACE", actionUp);
        m.getActionMap().put("released SPACE", actionRelUp);
    }

    @Override
    public void paint(Graphics g){
        g.drawLine(0, SIZE / 2, SIZE, SIZE / 2);
        g.setColor(Color.green);
        g.fillRect(x, y, width, height);
        m.repaint();
    }
}

我认为为跳转键添加“释放的密钥”会起作用,但是显然只有在按下然后释放按键时才会记录,而不是只要密钥被释放。那么,如何正确添加数学运算?此外,我确实意识到这个程序可能还有其他一些小问题,我计划在我通过角色跳跃和移动找出更多信息之后将其全部清理干净。

0 个答案:

没有答案