Sunday, January 18, 2015

Anansi: The Game Loop


The game we create is a 2D scrolling sh'm'up. So we need a game loop with gives us events at a given frame rate. There are various solutions to this, but we want to keep it simple for now. So the current choice for the game loop is an AnimationTimer.

The game loop basically looks like this:

  
package game;
 
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.stage.Stage;


public class Main extends Application {
 
 private double SCENE_WIDTH = 400;
 private double SCENE_HEIGHT = 800;
 
 private AnimationTimer timer;
 
 
 @Override
 public void start(Stage primaryStage) {
  try {

   // create root node
   Group root = new Group();
   
   // create scene
   Scene scene = new Scene( root, SCENE_WIDTH,SCENE_HEIGHT);
   
   // show stage
   primaryStage.setScene(scene);
   primaryStage.show();

   // start the game
   gameLoop();
   
  } catch(Exception e) {
   e.printStackTrace();
  }
 }

 private void gameLoop() {

  // game loop
        timer = new AnimationTimer() {
            @Override
            public void handle(long l) {
            
             // do something
             
            }
 
        };
        
        timer.start();
        
 }
 
 public static void main(String[] args) {
  launch(args);
 }
}

The AnimationTimer runs at 60 fps. Everything we do inside runs 60 times a second, so we need to be careful about the performance in that loop.

No comments:

Post a Comment