我目前正在编写一个游戏,其中两个对象根据键盘输入在一个窗口中移动。一个对象使用ASDW键移动,另一个对象使用箭头键移动。我目前正在使用KeyListener来执行此操作,但是KeyListener不能与同时输入一起使用,因此两个对象不能同时移动。我知道使用键绑定可以同时进行输入,但是我不知道如何实际使用键绑定。我尝试阅读有关它的Oracle教程,但这让我感到困惑。我想知道是否有人可以提供有关如何交换KeyListener以换取KeyBinding的替代教程?这也是我在这里的第一篇文章,如果格式设置已关闭,我深表歉意。
public class FightingBricks extends JPanel implements ActionListener,
KeyListener
{
Timer tm;
int x1 = 0, y1 = 0, velX1 = 0, velY1 = 0;
int x2 = 0, y2 = 0, velX2 = 0, velY2 = 0;
int w = 1000, h = 1000;
static int width = 1000, height = 1000;
public FightingBricks ()
{
tm = new Timer(2, this);
tm.start();
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.red);
g.fillRect(x1, y1, 50, 50);
g.setColor(Color.blue);
g.fillRect(x2, y2, 50, 50);
}
public void actionPerformed(ActionEvent e)
{
if(x1 < 0)
{
x1 = 0;
velX1 = 0;
}
if(x1 > w - 50)
{
x1 = w - 50;
velX1 = 0;
}
if(y1 < 0)
{
y1 = 0;
velY1 = 0;
}
if(y1 > h-75)
{
y1 = h-75;
velY1 = 0;
}
x1 = x1 + velX1;
y1 = y1 + velY1;
if(x2<0)
{
velX2 = 0;
x2 = 0;
}
if(x2>w-50)
{
velX2 = 0;
x2 = w-50;
}
(y2<0)
{
velY2 = 0;
y2 = 0;
}
if(y2>h-75)
{
velY2 = 0;
y2 = h-75;
}
y2 = y2 + velY2;
x2 = x2 + velX2;
repaint();
}
public void keyPressed(KeyEvent e)
{
int c = e.getKeyCode();
if (c == KeyEvent.VK_LEFT) // VK_Left is left arrow
{
velX1 = -2;
velY1 = 0;
}
if (c == KeyEvent.VK_UP) // VK_UP is up arrow
{
velX1 = 0;
velY1 = -2; // means up
}
if (c == KeyEvent.VK_RIGHT)
{
velX1 = 2;
velY1 = 0;
}
if (c == KeyEvent.VK_DOWN)
{
velX1 = 0;
velY1 = 2;
}
if(c == KeyEvent.VK_W)
{
velX2 = 0;
velY2 = -2;
}
if(c == KeyEvent.VK_A)
{
velX2 = -2;
velY2 = 0;
}
if(c == KeyEvent.VK_S)
{
velX2 = 0;
velY2 = 2;
}
if(c == KeyEvent.VK_D)
{
velX2 = 2;
velY2 = 0;
}
}
public void keyTyped(KeyEvent e){}
public void keyReleased(KeyEvent e)
{
velX1 = 0;
velY1 = 0;
velX2 = 0;
velY2 = 0;
}
public static void main(String[] args)
{
FightingBricks fb = new FightingBricks();
JFrame jf = new JFrame();
jf.setTitle("Fighting Bricks");
jf.setSize(width, height);
jf.setResizable(false);
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
FightingBricks fb1 = new FightingBricks();
jf.add(fb1);
}
}