Flickering images in java, BufferStrategy?

六月ゝ 毕业季﹏ 提交于 2020-01-23 11:44:33

问题


I'm making a game in java and need to paint units on a gameboard. I put all units in a list and paints every unit in that list. The paint method looks like this:

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

I have tried to make a BufferStrategy but it only makes the problem worse, guess I am doing something wrong.

Thanks


回答1:


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


来源:https://stackoverflow.com/questions/13858802/flickering-images-in-java-bufferstrategy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!