Sunday, February 1, 2015

Anansi: Background Scrolling - Revisited


Our background scrolling consists currently of an ImageView that's being relocated in the game loop. The whole ImageView. The relevant code for this:

public class Background extends SpriteBase {

 public Background(Pane layer, Image image, double x, double y, double speed) {
  super(layer, image, x, y, 0, 0, speed, 0, Double.MAX_VALUE, 0);
 }

 public void move() {
  
  super.move();
  
  checkBounds();
  
 }

 private void checkBounds() {
  
     // check bounds. we scroll upwards, so the y position is negative. once it's > 0 we have reached the end of the map and stop scrolling
     if( Double.compare( y, 0) >= 0) {
      y = 0;
     }
     
 }
 
 @Override
 public void checkRemovability() {
  // nothing to do
 }


}

When we take a look at the ImageView class, there's a method setViewPort. We could as well use that one. We only have to modify a few lines of code:

public class Background extends SpriteBase {

 public Background(Pane layer, Image image, double x, double y, double speed) {
  super(layer, image, x, y, 0, 0, speed, 0, Double.MAX_VALUE, 0);
  
  // we relocate to origin, the scrolling is done via setting the viewport
  getView().relocate(0, 0);
 }

 public void move() {
  
  super.move();
  
  checkBounds();
  
 }

 private void checkBounds() {
  
     // check bounds. we scroll upwards, so the y position is negative. once it's > 0 we have reached the end of the map and stop scrolling
     if( Double.compare( y, 0) >= 0) {
      y = 0;
     }
     
 }
 
 @Override
 public void checkRemovability() {
  // nothing to do
 }


 public void updateUI() {
  
  imageView.setViewport( new Rectangle2D( 0, -y, Settings.SCENE_WIDTH, Settings.SCENE_HEIGHT));

 }
}


In other words: Instead of relocating the ImageView in the updateUI method of the super class, we simply change the view port.

This gives us exactly the same visual result. It'll be interesting though how the internals of JavaFX work and what differences there are regarding performance in numbers. I couldn't see any performance gain or drop by using either of the solutions.

No comments:

Post a Comment