我一直在做一个游戏,但搞砸了一些东西,我不知道它是什么。在此示例中,我尽可能简化了代码,并且保留了相同的问题。
在此示例中,红色方块不是向上移动而不留下痕迹,而是留下红色轨迹,这意味着图形未正确处理或缓冲区策略不起作用。
如何让红场不留下痕迹?
import java.awt.*;
import java.awt.image.BufferStrategy;
import javax.swing.JFrame;
public class game extends Canvas implements Runnable {
private boolean running = false;
private int w = 1920/2, h = 1080/2, move = 300;
private JFrame frame;
private Thread thread;
public game() {
frame = new JFrame("Test");
frame.setPreferredSize(new Dimension(w,h));
frame.setMaximumSize(new Dimension(w,h));
frame.setMinimumSize(new Dimension(w,h));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.add(this);
frame.setVisible(true);
start();
setBackground(Color.black);
}
public synchronized void start() {
thread = new Thread(this);
thread.start();
running = true;
}
public void run() {
long lastTime = System.nanoTime();
double amountOfTicks = 60.0;
double ns = 1000000000 / amountOfTicks;
double delta = 0;
while(running){
long now = System.nanoTime();
delta += (now - lastTime) / ns;
lastTime = now;
while(delta >= 1) {
tick();
delta--;
}
if(running) render();
}
}
private void tick() {
move--;
}
private void render() {
BufferStrategy bs = this.getBufferStrategy();
if(bs == null) {
this.createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
g.setColor(Color.red);
g.fillRect(300, move, 50, 50);
g.dispose();
bs.show();
}
public static void main(String[] args) { new game(); }
}
如何让红场不留下痕迹?
g.setColor(Color.red);
g.fillRect(300, move, 50, 50);
在绘制红色方块之前,您需要绘制画布的整个背景。
g.setColor(...);
g.fillRect(...);
g.setColor(Color.red);
g.fillRect(300, move, 50, 50);