尝试使用箭头键和WASD

时间:2017-06-03 15:05:30

标签: java animation graphics awt keylistener

嘿伙计们我正在制作一个可以用WASD和箭头键移动角色的游戏。我让它们移动但我无法让它们同时移动。一个人不能移动其他形状移动。有没有办法同时检查WASD和箭头按下?希望你们能帮忙。提前谢谢。

以下是代码:

// The "SoccerGame" class.
import java.awt.*;
import java.applet.*;
import java.awt.event.*;

public class SoccerGame extends Applet implements KeyListener
{
    //x and y values of the player 1 and 2's character and the ball
    int x1 = 0, y1 = 275, x2 = 780, y2 = 275, xBall = 400, yBall = 275;

    public void init ()
    {
        this.requestFocus ();
        addKeyListener (this);

        //setting size of program
        setSize (800, 550);

    } // init method


    public void paint (Graphics g)
    {
        //Player 1
        g.setColor (Color.red);
        g.fillRect (x1, y1, 30, 30);

        //Player2
        g.setColor (Color.black);
        g.fillRect (x2, y2, 30, 30);

        //Ball
        g.setColor (Color.blue);
        g.fillRect (xBall, yBall, 30, 30);

    } // paint method


    public void keyPressed (KeyEvent e)
    {
        //Moving Player 1 with arrow Keys
        if (e.getKeyCode () == e.VK_W)
        {
            y1 = y1 - 10;
        }
        if (e.getKeyCode () == e.VK_S)
        {
            y1 = y1 + 10;
        }
        if (e.getKeyCode () == e.VK_A)
        {
            x1 = x1 - 10;
        }
        if (e.getKeyCode () == e.VK_D)
        {
            x1 = x1 + 10;
        }

        //Moving player 2 with WASD
        if (e.getKeyCode () == e.VK_UP)
        {
            y2 = y2 - 10;
        }
        if (e.getKeyCode () == e.VK_DOWN)
        {
            y2 = y2 + 10;
        }
        if (e.getKeyCode () == e.VK_LEFT)
        {
            x2 = x2 - 10;
        }
        if (e.getKeyCode () == e.VK_RIGHT)
        {
            x2 = x2 + 10;
        }



        repaint ();
    }


    public void keyReleased (KeyEvent e)
    {
    }


    public void keyTyped (KeyEvent e)
    {
    }
} // SoccerGame class

1 个答案:

答案 0 :(得分:0)

不要使用KeyListener(正如您在其他问题中所建议的那样)。

相反,您应该使用Key Bindings。然后,您需要跟踪已按下的键,并使用Swing Timer来安排动画。

查看Motion Using the Keyboard

KeyboardAnimation.java示例显示了如何做到这一点。