我正在尝试编写一个 Space Invader 游戏来提高我在 AP 计算机科学中学到的技能。我遇到了一个问题。当我按下空格键(发射按钮)时,子弹移动到顶部的动画不可见。相反,子弹只是出现在您开火的屏幕顶部。这是包含子弹发射的代码:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JPanel;
import javax.swing.Timer;
public class AlienInvader extends JPanel implements KeyListener, ActionListener {
Constants constant = new Constants();
Timer timer = new Timer(5, this);
Sprite images = new Sprite();
public void update() {
timer.start();
images.loadImage();
addKeyListener(this);
setFocusable(true);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLACK);
g.fillRect(0, 0, 500, 500);
g.drawImage(images.spaceship, constant.x, constant.y, null);
g.drawImage(images.bullet, constant.bulletx, constant.bullety, null);
}
@Override
public void keyPressed(KeyEvent e) {
System.out.println(constant.x);
switch (e.getKeyCode()) {
case KeyEvent.VK_LEFT:
constant.xvel = -1 * constant.STEP;
repaint();
break;
case KeyEvent.VK_RIGHT:
constant.xvel = 1 * constant.STEP;
repaint();
break;
case KeyEvent.VK_SPACE:
constant.xvel = 0;
constant.bulletx = constant.x;
constant.bullety = constant.y;
while (constant.bullety > 0) {
constant.bullety = constant.bullety - 1;
repaint();
}
}
constant.x += constant.xvel;
}
@Override
public void keyReleased(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_LEFT:
constant.xvel = -1;
break;
case KeyEvent.VK_RIGHT:
constant.xvel = 1;
break;
}
}
@Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
}
我将如何做到这一点,以便用户可以看到子弹在您开火时在屏幕上移动?