嘿,我正在制作一个游戏,其中可以用wasd and arrow键移动角色。我让他们移动,但我不能同时让他们移动。一个人不能移动另一个形状。有没有办法检查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
不要使用钥匙列者(正如您在其他问题中所建议的(。
相反,您应该使用Key Bindings
。然后,您需要跟踪已按下哪些键并使用Swing Timer
安排动画。
使用键盘查看运动。
KeyboardAnimation.java
示例显示了如何完成的。