0

For some reason everyone sets their BufferStrategy to the BufferStrategy in their canvas whenever they render their game.

BufferStrategy bs;
Graphics2D g;

private void render() {
        bs = window.getCanvas().getBufferStrategy();

        if (bs == null) {
            window.getCanvas().createBufferStrategy(3);
            return;
        }

        g = (Graphics2D) bs.getDrawGraphics();

        bs.show();
        g.dispose();
}

// When thread starts
public void run() {
    while (running) {
       //Game loop stuff here.
       render();
      }
    }

Can you just set it once instead of every time the game re-renders?

  • 1
    First, you need to understand the concept of page flipping. Second, you code will only create a new strategy if one doesn’t exist (or has been invalidated for some reason). If you read the JavaDocs and the tutorial examples, you’ll find that this is (generally) the recommended way to achieve this – MadProgrammer Apr 25 '18 at 05:17
  • Have a look at [the JavaDocs](https://docs.oracle.com/javase/8/docs/api/java/awt/image/BufferStrategy.html) for a basic example. One of reasons for doing it the way you’ve seen is that the render thread may start before the window is realised, which is the only time a strategy can be created – MadProgrammer Apr 25 '18 at 05:22
  • @MadProgrammer I understand that, but every time the method gets called the bufferStrategy is getting set to the canvas bufferStrategy again. –  Apr 25 '18 at 06:31
  • No, it's not. `createBufferStrategy` is only getting called if the result of `getBufferStrategy` is `null` (hasn't yet been created). So, yes, you MUST call `getBufferStrategy` each time, as it can change – MadProgrammer Apr 25 '18 at 06:32
  • I mean bs is being set to the BufferStrategy again. ( bs = window.getCanvas().getBufferStrategy(); ) –  Apr 25 '18 at 06:46
  • So, two problems. One, it's hard to know when a `Canvas` will be in a valid state to create a strategy and the strategy could be changed or reset for any number of reasons. Do you need to keep a instance reference, I wouldn't think so. – MadProgrammer Apr 25 '18 at 07:11

0 Answers0