gpt4 book ai didi

java - 你如何在java中为游戏加倍缓冲?

转载 作者:搜寻专家 更新时间:2023-10-31 08:07:03 24 4
gpt4 key购买 nike

所以在我正在开发的游戏中,我有一个弹珠跟随鼠标,但是当它这样做时屏幕会闪烁。

背景包括两个 jpeg 和 9 个矩形。我将如何进行双缓冲呢?这是主窗口的代码。

/**
* Write a description of class Window here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Window extends JApplet implements MouseMotionListener
{
private BufferedImage image;
private BufferedImage side;
private int mouseX;
private int mouseY;

public Window(){
try {
image = ImageIO.read(new File("Backgrounds/violet.jpg"));
side = ImageIO.read(new File("Backgrounds/side margin.jpg"));
} catch (IOException ex) { }
}

private void delay(int delay)
{
try {
Thread.sleep(delay);
} catch (InterruptedException e) {}
}

public void init()
{
this.addMouseMotionListener(this);
}

public void paint (Graphics page)
{
page.drawImage(image, 0, 0, null);
page.setColor(Color.blue);
page.fillRect(0, 0, 160, 160);
page.setColor(Color.black);
page.fillRect(15, 15, 130, 130);
page.setColor(Color.green);
page.fillRect(340, 0, 160, 160);
page.setColor(Color.black);
page.fillRect(355, 15, 130, 130);
page.setColor(Color.yellow);
page.fillRect(0, 340, 160, 160);
page.setColor(Color.black);
page.fillRect(15, 355, 130, 130);
page.setColor(Color.red);
page.fillRect(340, 340, 160, 160);
page.setColor(Color.black);
page.fillRect(355, 355, 130, 130);
page.drawImage(side, 500, 0, null);
page.drawString(Score.getScore(), 560, 110);
//conveyors
page.setColor(Color.gray);
page.fillRect(235, 0, 30, 160);

//marble
delay(100);

page.fillOval(mouseX, mouseY , 40, 40);
}

public void mouseMoved(MouseEvent e)
{
mouseX = e.getX();
mouseY = e.getY();
repaint();
}

public void mouseDragged(MouseEvent e)
{

}
}

最佳答案

双缓冲在概念上非常简单,不是一个一个地绘制对象,而是在图像上绘制它们,然后告诉渲染器绘制整个图像。这消除了闪烁。

这是您如何执行此操作的示例 (source)

class DoubleBufferedCanvas extends Canvas {

public void update(Graphics g) {
Graphics offgc;
Image offscreen = null;
Dimension d = size();

// create the offscreen buffer and associated Graphics
offscreen = createImage(d.width, d.height);
offgc = offscreen.getGraphics();
// clear the exposed area
offgc.setColor(getBackground());
offgc.fillRect(0, 0, d.width, d.height);
offgc.setColor(getForeground());
// do normal redraw
paint(offgc);
// transfer offscreen to window
g.drawImage(offscreen, 0, 0, this);
}
}

如今,您不必自己实现它,您可以使用 BufferStrategy 和相关类。有关示例,请参见 lakam99 的回答。

关于java - 你如何在java中为游戏加倍缓冲?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10508042/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com