Friday, January 23, 2015

Anansi: Debug Overlay


Before we add the sprites we need should ensure that we have debug information. There'll be lots of sprites and we want to verify that all of them are removed from memory so that we don't get memory leaks.

We keep the code from the prototype and move it to a dedicated method, so that we don't clutter the game loop.

We stick with the label that contains the debug information. During gameplay we have the visual focus on the top of the playfield, so we position the debug information on the bottom of the screen. Moreover we'd like to have it stick out a bit. JavaFX gives us great and easy to use tools to make a semi-transparent background.

To make things short, here's the code. It's similar to the one of the prototype with the exception that the width of the overlay spans over the entire screen and that it's attached to the bottom. You can use JavaFX's bind methods to achieve that.

We create the overlay
private void createDebugOverlay() {
 
 // debug info container
 debugLabel = new Label();
 debugLabel.setTextFill(Color.RED);
 
 // add to layer
 debugLayer.getChildren().add( debugLabel);
 
 // semi-transparent gray background
 debugLayer.setStyle("-fx-background-color:rgba(0,0,0,0.3)");

 // stretch the layer horizontally 
 debugLayer.prefWidthProperty().bind(primaryStage.getScene().widthProperty());
 
 // bind the layer to the bottom of the screen,
 debugLayer.layoutYProperty().bind(primaryStage.getScene().heightProperty().subtract(debugLayer.heightProperty()));
 
}


And a method for calculating the FPS which we invoke in our game loop.
// counter for game loop
int frameCount = 0;
int fpsCurrent = 0;
long prevTime = -1;
...
private void updateFps() {
 
   frameCount++;
   
   long currTime = System.currentTimeMillis();
   
   if( currTime - prevTime >= 1000) {
    
    // get current fps
    fpsCurrent = frameCount;

    // reset counter every second
    prevTime = currTime;
    frameCount = 0;
   }
   
}

We update the debug container with the information we wish to display.
private void updateDebugOverlay() {

   // show debug info
   // ---------------------------
   debugLabel.setText("FPS: " + fpsCurrent);

}

And extend the game loop with the just created methods:
private void createGameLoop() {

  gameLoop = new AnimationTimer() {
   
      @Override
      public void handle(long l) {
       
       ...

       // calculate fps and show it
       // ---------------------------
       updateFps();
       
       // show debug information (fps etc)
       // --------------------------------
       updateDebugOverlay();
      }

  };
  
}

No comments:

Post a Comment