我正在编写一个游戏,我正在使用 Java 的 Swing。现在我正试图让 KeyListeners 和 Action 监听器工作。
我想要做的是让我的对象根据我按下的键移动。(左,右,上,下),但由于某种原因,当我按下这些键中的任何一个时,什么都没有发生,但是当我同时按下其中的 3 个键时。物体奇怪地向左移动..
所以这是我创建 Runner 对象的类的代码:
import java.awt.*;
public class Runner{
private int xpos, ypos, base, side;
public Runner(int b, int h ) {
base = b;
side = h;
}
public void setPosition(int x, int y){
xpos = x;
ypos = y;
}
public void view(Graphics g) {
int x[] = { xpos, xpos-base/2, xpos + base/2};
int y[] = { ypos, ypos + side, ypos + side };
g.setColor(Color.lightGray);
g.fillPolygon( x, y, 3 );
g.setColor(Color.darkGray);
g.drawLine(xpos, ypos, xpos, ypos + side);
}
public void shoot(Graphics g){
g.setColor(Color.red);
g.drawLine(xpos,ypos, xpos, 0);
}
}
这是假设运行该死的东西的代码:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class RunningGame extends JPanel implements KeyListener, ActionListener{
Runner rs;
int x,y;
Timer t;
boolean shot = false;
boolean left = false, right = false, up = false, down = false;
public RunningGame() {
x = 100;
y = 150;
rs = new Runner(40,60);
rs.setPosition(x,y);
this.addKeyListener(this);
this.setBackground(Color.black);
t = new Timer(40, this);
t.start();
}
public void paintComponent(Graphics g){
super.paintComponent(g);
rs.view(g);
if(shot) rs.shoot(g);
}
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == 37) {left = true;}
if (e.getKeyCode() == 39) {right = true;}
if (e.getKeyCode() == 38) {up = true;}
if (e.getKeyCode() == 40) {down = true;}
if (e.getKeyCode() == 32) {shot = true;}
rs.setPosition(x,y);
this.repaint();
}
public void keyReleased(KeyEvent e){
if (e.getKeyCode() == 37) left = false;
if (e.getKeyCode() == 39) right = false;
if (e.getKeyCode() == 38) up = false;
if (e.getKeyCode() == 40) down = false;
if (e.getKeyCode() == 32) shot = false;
this.repaint();
}
public void keyTyped(KeyEvent e){}
public void actionPerformed(ActionEvent e) {
if (left) {
if(right){
right = false;
x = x - 10; shot = false;
}
}
if (right) {
if(left){
left = false;
x = x + 10; shot = false;
}
}
if (up) {
if(down){
down = false;
y = y - 10; shot = false;
}
}
if (down) {
if(up){
up = false;
y = y + 10; shot = false;
}
}
rs.setPosition(x,y);
this.repaint();
}
public static void main(String[] args) {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(300, 300); f.setLocation(100,100);
f.setTitle("Running");
RunningGame p = new RunningGame();
f.add(p); f.setVisible(true);
p.requestFocus();
}
}
(这不是最终代码,它只是使用宇宙飞船的示例,稍后我将使用不同的对象,只是想测试 KeyListener 和 ActionListener 以便它在继续之前工作。)
Anyways can anyone help me make the space ship move smoothly? and without having to release all keys to activate another? i.e If i hold left i want it to be able to press another button. so that if i press right, the space ship will start to move in that direction instead.
//MrElephants