【问题标题】:Trying to move two objects at the same time with arrow keys and WASD尝试使用箭头键和 WASD 同时移动两个对象
【发布时间】:2017-11-04 19:58:50
【问题描述】:

大家好,我正在制作一款可以使用 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

【问题讨论】:

    标签: java animation graphics awt keylistener


    【解决方案1】:

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

    您应该使用Key Bindings。然后,您需要跟踪按下了哪些键并使用Swing Timer 来安排动画。

    查看Motion Using the Keyboard

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-19
      • 1970-01-01
      • 2022-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多