Java 尝试使用箭头键和WASD同时移动两个对象
嘿,伙计们,我正在制作一个游戏,游戏中的角色可以用WASD和箭头键移动。我让他们移动,但我不能让他们同时移动。一个形状不能移动,另一个形状不能移动。有没有办法同时检查WASD和arrow按钮?希望你们能帮忙。提前谢谢 代码如下:Java 尝试使用箭头键和WASD同时移动两个对象,java,animation,graphics,awt,keylistener,Java,Animation,Graphics,Awt,Keylistener,嘿,伙计们,我正在制作一个游戏,游戏中的角色可以用WASD和箭头键移动。我让他们移动,但我不能让他们同时移动。一个形状不能移动,另一个形状不能移动。有没有办法同时检查WASD和arrow按钮?希望你们能帮忙。提前谢谢 代码如下: // The "SoccerGame" class. import java.awt.*; import java.applet.*; import java.awt.event.*; public class SoccerGame extends Applet im
// 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
不要使用KeyListener(正如其他问题中所建议的那样)
相反,您应该使用键绑定
。然后,您需要跟踪已按下的关键点,并使用摆动计时器来安排动画
退房
KeyboardAnimation.java
示例演示了如何实现这一点