Libgdx - Parallax background set horizontally, can't implement scrolling up and down

125 Views Asked by At

I found a tutorial online to create a horizontally scrolling parallax background with this custom class:

public class ParallaxBackground extends Actor {

private float scroll;
private Array<Texture> layers;
private final int LAYER_SPEED_DIFFERENCE = 2;

float x, y, width, height, scaleX, scaleY;
float originX, originY, rotation;
float srcX, srcY;
boolean flipX, flipY;

private float speed;

public ParallaxBackground(Array<Texture> textures, HeroKnight player) {
    layers = textures;
    for(int i = 0; i <textures.size;i++){
        layers.get(i).setWrap(Texture.TextureWrap.MirroredRepeat, Texture.TextureWrap.MirroredRepeat);
    }
    scroll = 0;
    speed = 0;

    x = y = originX = originY = rotation = 0;
    srcY = 0;
    width =  Gdx.graphics.getWidth();
    height = Gdx.graphics.getHeight();
    scaleX = scaleY = 1;
    flipX = flipY = false;
}

public void setSpeed(float newSpeed){
    this.speed = newSpeed;
}

public void update(float deltaTime) {

}

@Override
public void draw(Batch batch, float parentAlpha) {
    batch.setColor(getColor().r, getColor().g, getColor().b, getColor().a * parentAlpha);

    scroll+=speed;
    srcX = scroll;
    batch.draw(layers.get(0), x, y, originX, originY, width, height, scaleX, scaleY, rotation, (int)srcX, (int) srcY, layers.get(0).getWidth(), layers.get(0).getHeight(), flipX, flipY);
    for(int i = 1;i<layers.size;i++) {
        srcX = scroll + i*this.LAYER_SPEED_DIFFERENCE *scroll;
        batch.draw(layers.get(i), x, y, originX, originY, width, height,scaleX,scaleY,rotation,(int)srcX,(int)srcY,layers.get(i).getWidth(),layers.get(i).getHeight(),flipX,flipY);
    }
}

.

backgroundViewport = new ScreenViewport();
    stage = new Stage(backgroundViewport);

    Array<Texture> textures = new Array<Texture>();
    for(int i = 1; i <= 5;i++){
        textures.add(new Texture(Gdx.files.internal("images/"+ i+".png")));
        textures.get(textures.size-1).setWrap(Texture.TextureWrap.MirroredRepeat, Texture.TextureWrap.MirroredRepeat);
    }
parallaxBackground = new ParallaxBackground(textures, player);
    parallaxBackground.setSize(Gdx.graphics.getWidth(),Gdx.graphics.getHeight());
    parallaxBackground.setSpeed(0);
    stage.addActor(parallaxBackground);

In the render method:

stage.act();
stage.draw();

Eveything works well when you are moving left to right. However, on my background image there is water down, so logically I want the screen to show it when the player is on the lower platforms, and make it scroll higher so that the water disappears when you go up.

So the question is: how do I make the blue part visible when the player is lower, and scroll it to the red part when you go higher?

enter image description here

0

There are 0 best solutions below