【发布时间】: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