我试图并排绘制单个矩形(未填充)以制作地板,然后以恒定速度移动整个地板。我的问题是,当他们向左移动时,屏幕不会刷新或删除前一个屏幕,因此几秒钟后,矩形设置为纯色。
这是我的代码。 我想了解如何加载屏幕,然后更新值,删除旧屏幕并显示新屏幕?
FRAME CLASS:
package Main;
import java.awt.Dimension;
import javax.swing.JFrame;
public class Frame extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
public static Dimension frameDim;
public Game game;
public JFrame frame;
public static int WIDTH= 800;
public static int HEIGHT= 400;
public Frame(Game game) {
frameDim = new Dimension(WIDTH, HEIGHT);
frame = new JFrame("TileJumper");
frame.setFocusable(true);
game.setPreferredSize(frameDim);
frame.add(game);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setResizable(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
game.start();
}
}
游戏类:
public class Game extends Canvas implements Runnable {
/**
*
*/
private static final long serialVersionUID = 1L;
public Thread thread;
public boolean running = false;
public double xmap = 0;
public int tileSize = 20;
public Font titleFont;
public String title = "Tile Jumper";
public int WIDTH;
public int HEIGHT;
public Graphics g;
public BufferStrategy bs;
public synchronized void start(){
if(running){
return;
}
running = true;
thread = new Thread(this);
thread.start();
}
public void init(){
setBackground(Color.black);
titleFont = new Font("Dialog", 0,28);
}
public void tick(){
xmap -= .1;
}
public void render(){
bs = this.getBufferStrategy();
if(bs == null) {
this.createBufferStrategy(3);
return;
}
bs = this.getBufferStrategy();
g = bs.getDrawGraphics();
g.setColor(Color.blue);
g.drawRect(275, 50, 250, 50);
g.setColor(Color.white);
g.setFont(titleFont);
g.drawString(title, 330, 85);
for(int i = 0; i < 100; i++){
g.drawRect((int)(xmap + i*tileSize), 350, tileSize, tileSize);
}
g.dispose();
bs.show();
//Toolkit.getDefaultToolkit().sync();
}
public void run() {
init();
long lastTime = System.nanoTime();
double numTicks = 60.0;
double ns = 1000000000/numTicks;
double delta = 0;
long timer = System.currentTimeMillis();
int updates = 0;
int frames = 0;
while(running){
long currentTime = System.nanoTime();
delta += (currentTime - lastTime)/ns;
lastTime = currentTime;
while(delta>=1){
tick();
updates++;
delta--;
}
render();
frames++;
if(System.currentTimeMillis() - timer > 1000){
timer += 1000;
System.out.println("FPS = " + frames + " TICK = " + updates);
frames = 0;
updates = 0;
}
}
}
public static void main(String [] args){
new Frame(new Game());
}
}
答案 0 :(得分:0)
g.dispose()
无法清除屏幕。
g = bs.getDrawGraphics();
之后
你必须自己做。
g.setColor(Color.black);
g.fillRect(0,0,getWidth(),getHeight());