Java中的闪烁图像,BufferStrategy?

3

我正在使用Java制作游戏,需要在游戏板上绘制单位。我将所有单位放入列表中,并绘制该列表中的每个单位。绘图方法如下:

  public void paint(Graphics g) {
        super.paint(g);

        if (unitList != null) {
            Collections.sort(unitList);
            for (Unit unit : unitList) {
                Image image = unit.getImage();
                g.drawImage(
                        image,
                        (int) (playPosition.x + unit.getPosition().getX() - image
                                .getWidth(null) / 2), (int) (playPosition.y
                                + unit.getPosition().getY() - image
                                .getHeight(null) / 2), null);
            }
        }
    }

我尝试创建了一个BufferStrategy,但是这只会让问题变得更糟,我猜我做错了什么。

谢谢。


4
重写paintComponent()而不是paint()方法。 - StanislavL
1
可能是由于 Collections.sort(unitList); 引起的,没有人知道,所以在使用 paintComponent 之前要做好准备。 - mKorbel
3
@user1900750 这个问题无法回答,为了更快地获得帮助,请发布一个SSCCE,即简短、可运行、可编译的示例。 - mKorbel
1
正如mKorbel所说,很难回答这个问题,但是请看一下我的答案,其中展示了Java中的一些游戏循环/逻辑:https://dev59.com/3WvXa4cB1Zd3GeqPOfTh#13827649 - David Kroukamp
1
例如:(https://dev59.com/UXA75IYBdhLWcg3wg5Vh#3256941)。 - trashgod
不要使用排序,而是使用像TreeSet这样的SortedSet。这也会减少并发问题和更改次数。在应用程序中最好使用ImageIO.read或getResource而不是异步读取部分图像。 - Joop Eggen
1个回答

0

Maybe you haven't implemented BufferStrategy correctly.
Try manual double buffering by doing offscreen painting on an Image, and then just paint the whole said image in your regular overriden paint() method.

You would do that like so:

// Double buffering objects.
Image doubleBufferImage;
Graphics doubleBufferGraphics;

/*
 * Onscreen rendering.
 */
 @Override
 public void paint(Graphics g) {
     doubleBufferImage = createImage(getWidth(), getHeight());
     doubleBufferGraphics = doubleBufferImage.getGraphics();
     paintStuff(doubleBufferGraphics);
     g.drawImage(doubleBufferImage, 0, 0, this);
 }

/*
 * Offscreen rendering.
 */
 public void paintStuff(Graphics g) {
     if (unitList != null) {
        Collections.sort(unitList);
        for (Unit unit : unitList) {
            Image image = unit.getImage();
            g.drawImage(
                    image,
                    (int) (playPosition.x + unit.getPosition().getX() - image
                            .getWidth(null) / 2), (int) (playPosition.y
                            + unit.getPosition().getY() - image
                            .getHeight(null) / 2), null);
        }
    }
 }


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接