我试图让一个简单的精灵在我的屏幕上移动。我无法弄清楚这段代码有什么问题,因为我遵循了来自不同源代码的说明,但删除了其他代码中其他功能添加的一些复杂性。现在我只是想让它在屏幕上自由移动。后来我打算让动画在移动时改变。这两个类的代码如下。
package game;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JPanel;
import javax.swing.Timer:
public class Game extends JPanel implements ActionListener {
int x, y, b_width, b_height;
Player player;
Timer timer;
public Game() {
addKeyListener(new KeyRecorder());
player = new Player();
timer = new Timer(5, this);
timer.start();
}
public void paint(Graphics g){
g.drawImage(player.image, player.getX(), player.getY(), this);
}
@Override
public void actionPerformed(ActionEvent e) {
player.move();
repaint();
}
public class KeyRecorder extends KeyAdapter{
public void keyPressed(KeyEvent e){
player.keyPressed(e);
repaint();
}
public void keyReleased(KeyEvent e){
player.keyReleased(e);
}
}
}
和精灵:
package game;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyEvent;
import javax.swing.ImageIcon;
public class Player {
private String sprite = "sprite.png";
int x, y, dx, dy;
int width, height;
Image image;
public Player() {
ImageIcon ii = new ImageIcon(this.getClass().getResource(sprite));
image = ii.getImage();
}
public int getX(){
return x;
}
public int getY(){
return y;
}
public void move() {
x = x + dx;
y = y + dy;
}
public void keyPressed(KeyEvent e){
int key = e.getKeyCode();
if(key == KeyEvent.VK_UP){
dy -= 3;
}
if(key == KeyEvent.VK_DOWN){
dy += 3;
}
if(key == KeyEvent.VK_LEFT){
dx -= 3;
}
if(key == KeyEvent.VK_RIGHT){
dx += 3;
}
}
public void keyReleased(KeyEvent e){
int key = e.getKeyCode();
if(key == KeyEvent.VK_UP){
dy -= 0;
}
if(key == KeyEvent.VK_DOWN){
dy += 0;
}
if(key == KeyEvent.VK_LEFT){
dx -= 0;
}
if(key == KeyEvent.VK_RIGHT){
dx += 0;
}
}
}