我正在用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,但这只会使问题变得更糟,猜猜我做错了什么。

谢谢

最佳答案

也许您没有正确实现BufferStrategy
尝试通过在Image上进行屏幕外绘画来进行手动双缓冲,然后仅以常规覆盖的paint()方法绘画整个图像。您将这样做:

// 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);
        }
    }
 }

07-24 09:34