我一直在开发一款游戏,但搞砸了一些东西,我不知道它是什么。我在这个例子中尽可能地简化了代码,但它仍然存在同样的问题。
在此示例中,红色方 block 不是向上移动而不留下痕迹,而是留下红色痕迹,这意味着图形未正确处理或缓冲策略不起作用。
如何让红色方 block 不留下痕迹?
<小时/>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(); }
}
最佳答案
How do I make the red square not leave behind a trail?
g.setColor(Color.red);
g.fillRect(300, move, 50, 50);
在绘制红色方 block 之前,您需要绘制 Canvas 的整个背景。
g.setColor(...);
g.fillRect(...);
g.setColor(Color.red);
g.fillRect(300, move, 50, 50);
关于java - 如何在 Java 中阻止重新绘制以前的图形?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43838786/