我正在用Java编写一个小游戏,但有一个小问题。所有渲染的帧都保留在屏幕上,因此,如果我移动图像,它将继续渲染更多图像,但是我希望图像在屏幕上移动。我究竟做错了什么?
public void tick(){
balk.tick();
}
public void render(){
BufferStrategy bs = this.getBufferStrategy();
if(bs==null){
createBufferStrategy(2);
return;
}
Font myFont = new Font ("Courier New", 1, 50);
Graphics g = bs.getDrawGraphics();
///////////////////////////////
g.drawImage(balk.getBalk(), balk.getX(), 900, this);
g.setFont(myFont);
g.drawString("Score: " + 0, 50, 100);
///////////////////////////////
//g.dispose();
bs.show();
}
public void init(){
frame = new JFrame();
WIDTH = (int)Toolkit.getDefaultToolkit().getScreenSize().getWidth();
HEIGHT = (int)Toolkit.getDefaultToolkit().getScreenSize().getHeight();
}
public static void main(String[] args){
Game game = new Game();
game.init();
game.setPreferredSize(new Dimension(WIDTH, HEIGHT));
game.setMaximumSize(new Dimension(WIDTH, HEIGHT));
game.setMinimumSize(new Dimension(WIDTH, HEIGHT));
frame.add(game);
frame.setUndecorated(true);
frame.setTitle("Ping Pong");
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setLayout(null);
frame.addKeyListener(new KeyListener(){
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if(key == KeyEvent.VK_A){
balk.setVelX(-5);
}
if(key == KeyEvent.VK_D){
balk.setVelX(5);
}
}
public void keyReleased(KeyEvent e) {
balk.setVelX(0);
}
public void keyTyped(KeyEvent arg0) {}
});
frame.setVisible(true);
game.start();
}
}
最佳答案
在绘制任何带有fillRect的东西之前,请清除屏幕,该fillRect会以您喜欢的颜色填充您的窗口。
g.setColor(Color.black);
g.fillRect(0, 0, width, height);
//draw here
这样的事情。