How to make an infite scrolling background?

I’m trying to make the background of my game infintely scroll as the user plays it (parallax scrolling).
So far I have:

void ofApp::setup(){
	ofSetFrameRate(30);
	background.load("bg1.png");
	yBgPos = 0;
}

//--------------------------------------------------------------
void ofApp::update(){
	yBgPos -= 5;
}

//--------------------------------------------------------------
void ofApp::draw(){
	background.draw(0, yBgPos);

But I’m not sure how to actually make the background repeat.

Hi @eugot , an ofShader would work well for this, probably rendering into an ofFbo. Also ofTexture::setTextureWrap() can set the how a texture wraps (GL_MIRRORED_REPEAT for example).

Hi @eugot

for a quick and dirty fix you can keep repeating the image by simply drawing it twice, so that as it moves up any exposed screen is covered, then re-set the drawposition when image one is being drawn off the screen - like this…

void ofApp::update(){
    yBgPos -= 5;
    if (yBgPos < - background.getHeight()) {
        yBgPos = 0;
    }
}

//--------------------------------------------------------------
void ofApp::draw(){
    background.draw(0, yBgPos);
    background.draw(0, yBgPos + background.getHeight() );
}
1 Like

Hey danb’s suggestion is fantastic! You can draw something upside down too if you need to:

background.draw(0, yBgPos, background.getWidth(), -background.getHeight());
1 Like