问题是,如果我按住其中一个箭头键,则在不断移动之间会有延迟。我的意思是,如果我按住左键,它会移动 7 个像素,然后稍等一下,它会不断移动。有人可以告诉我如何解决这个问题,让它“顺利”移动
代码 - - - - - - - - - -
打包游戏;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
public class GamePlay implements KeyListener{
int shipX = 400;
int shipY = 300;
public int shipSpeed = 7;
public void incShipX(int i) {this.shipX += i;}
public void incShipY(int i) {this.shipY += i;}
Image ship;
File shipFile = new File("C:/Users/Pictures/ship.png");
public GamePlay() {
try {
ship = ImageIO.read(shipFile);
} catch (IOException ex) {
Logger.getLogger(GamePlay.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void drawShip(Graphics g) {
g.drawImage(ship, shipX, shipY, null);
}
@Override
public void keyTyped(KeyEvent ke) {
}
@Override
public void keyPressed(KeyEvent ke) {
if(ke.getKeyCode() == KeyEvent.VK_LEFT) {
incShipX(-shipSpeed);
}
if(ke.getKeyCode() == KeyEvent.VK_RIGHT) {
incShipX(shipSpeed);
}
if(ke.getKeyCode() == KeyEvent.VK_UP) {
incShipY(-shipSpeed);
}
if(ke.getKeyCode() == KeyEvent.VK_DOWN) {
incShipY(shipSpeed);
}
}
@Override
public void keyReleased(KeyEvent ke) {
}
}
我将 keyListener 添加到我的 Canvas --- add(gamePlay);