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

1 回答 1

0

也许你没有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);
        }
    }
 }
于 2012-12-16T12:15:03.527 回答