4
\$\begingroup\$

I am trying to develop a little game using libGDX. We have a hero who jumps and world consist of dynamically created moving platforms in an auto side-scrolling manner. I wanted background to scroll at half speed of foreground objects to establish a moving background effect.

For this I came up with this idea: Have a 1024px X 240px image and each time render executes select a 256px X 240px region from that texture according to backgroundObject X position. Something like this:

portioned bg

And this is my code:

    bgTexture = new Texture(Gdx.files.internal("data/bg.png"));
    bgTexture.setFilter(Texture.TextureFilter.Nearest, Texture.TextureFilter.Nearest);

And this code executes inside render method.

    bgRegion= new TextureRegion(bgTexture, -1 * (int)bgObj.getX(),0,256,240); //bgObj is a scrollable object where in each update changes X value of position(Vector2): moves left.
    bgRegion.flip(false, true);

    batcher.draw(bgRegion, 0, 0, Variables.ScreenWidth / 2, Variables.ScreenHeight / 2);

Now, I am wondering if there is a better method to implement this effect? My method seems to have high system resource cost.

\$\endgroup\$
5
\$\begingroup\$

Don't keep newing up TextureRegions, try re-using one and just change the parameters of that.

private TextureRegion bgRegion;

public void create() {
    bgRegion= new TextureRegion(bgTexture, -1 * (int)bgObj.getX(),0,256,240); //bgObj is a scrollable object where in each update changes X value of position(Vector2): moves left.
}

public void draw() {
    // Update the region here
    bgRegion.setRegionX(-1 * (int)bgObj.getX());
    batcher.draw(bgRegion, 0, 0, Variables.ScreenWidth / 2, Variables.ScreenHeight / 2);
}
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ I did as you described, also today I learned a new function setRegionX thanks to you. You rock! \$\endgroup\$ – raidensan Sep 18 '15 at 12:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.