1

I am trying to implement double buffering for a game, but I am not sure if I am doing it correctly.

I am calling this.repaint() in my main game loop, which then should do this:

@Override
public void paint(Graphics g){
    // this.getWidth() / this.getHeight() is the window size
    this.dbImage = createImage(this.getWidth(), this.getHeight());
    this.dbg = dbImage.getGraphics();
    this.paintComponent(dbg);
    g.drawImage(this.dbImage, 0, 0, this);
}

@Override
public void paintComponent(Graphics g){
    try{
        g.drawImage(bg, 0, 0, this);
        // gameObjects is an ArrayList with an object in it that represents 
        // an item on the screen, such as an enemy or a bullet
        for(int i = 0; i < gameObjects.size(); i++){
            GameObject go = gameObjects.get(i);
            g.drawImage(go.getSprite(), go.getX(), go.getY(), this);
        }
    }catch(Exception e){
    }
}

I basically did what this guy does here: YouTube Video The issue I am having, is that it seems to be running worse that before I had the double buffering. At times items freeze for half a second then catches back up and it runs normal, then it happens again within a few minutes (or less).

Get Off My Lawn
  • 34,175
  • 38
  • 176
  • 338

1 Answers1

0

Create an image, create a buffer for that image, then do all drawing on the buffer so it doesnt get painted to screen for every single drawing operation. When all done for a whole frame, you draw that image really on screen now.

In init:

offscreen = createImage(dim.width,dim.height); 
bufferGraphics = offscreen.getGraphics(); 

In drawing part(whatever you want on buffer):

 bufferGraphics.fillRect(20, 20+m,0,20);

In drawing screen when all done:

  g.drawImage(offscreen,0,0,this); 

If these doesnt satisfy, there is triple buffering too.

huseyin tugrul buyukisik
  • 11,469
  • 4
  • 45
  • 97