How can i make an endless scrolling background?

edited January 2017 in Questions about Code

Hello, ive been trying to make an endless scrolling background, but it stops after a while. Anyone got any tips?

PImage img;
int x; 
void setup(){
size(1080,500);
img = loadImage("city_3.png");
}

void draw(){
//image(img, 0, 0);
background(300);
x = constrain(x, 0, img.width - width); 
image(img, -x, 0);
x = frameCount; 

}

Answers

  • what does city3.png look like? does it wrap? is it bigger than the screen or smaller?

  • edited January 2017

    It is 2973x532. So it's bigger then the screen.

  • Answer ✓

    this works, but might be inefficient by drawing more than it needs

    this requires img to be the same height as the screen but the background can be shorter, the same as or wider than the screen.

    void draw() {
      int x = frameCount % img.width;
      for (int i = -x ; i < width ; i += img.width) {
        copy(img, 0, 0, img.width, height, i, 0, img.width, height);
      }
    }
    
  • Thank you so much!

  • edited January 2017 Answer ✓

    um, ok, given the size, it'll be more efficient to drop the loop and basically copy from framecount % img.width to the end of the image. then, if necessary, copy from 0, 0 of the image to the undrawn part of the screen

    which will start at img.width - (framecount % img.width), i think.

    so

    void draw() {
      // NB image is wider than screen
      int x = frameCount % img.width;
      copy(img, x, 0, img.width, height, 0, 0, img.width, height);
      int x2 = img.width - x;
      if (x2 < width) {
        copy(img, 0, 0, img.width, height, x2, 0, img.width, height);
      }
    }
    
  • (um, that still copies img.width columns but hopefully copy() is intelligent enough to know to crop the ones off screen, which saves us a job)

  • Both of them seems to work, so thank you so much! I will let you know if there are any problems when i manage to add a game character in!

  • yeah, both work, but the second is optimised for backgrounds larger than the screen, the first will work with any image.

  • Ahh, ok :) Thank you so much again!

Sign In or Register to comment.