LibGDX has classes for this:
public class ParallaxLayer {
public TextureRegion region ;
public Vector2 parallaxRatio;
public Vector2 startPosition;
public Vector2 padding ;
public ParallaxLayer(TextureRegion region,Vector2 parallaxRatio,Vector2 padding){
this(region, parallaxRatio, new Vector2(0,0),padding);
}
/**
* @param region the TextureRegion to draw , this can be any width/height
* @param parallaxRatio the relative speed of x,y {@link ParallaxBackground#ParallaxBackground(ParallaxLayer[], float, float, Vector2)}
* @param startPosition the init position of x,y
* @param padding the padding of the region at x,y
*/
public ParallaxLayer(TextureRegion region, Vector2 parallaxRatio, Vector2 startPosition, Vector2 padding){
this.region = region;
this.parallaxRatio = parallaxRatio;
this.startPosition = startPosition;
this.padding = padding;
}
}
And:
public class ParallaxBackground {
private ParallaxLayer[] layers;
private OrthographicCamera camera;
private SpriteBatch batch;
private Vector2 speed = new Vector2();
/**
* @param layers The background layers
* @param width The screenWith
* @param height The screenHeight
* @param speed A Vector2 attribute to point out the x and y speed
*/
public ParallaxBackground(ParallaxLayer[] layers,float width,float height,Vector2 speed){
this.layers = layers;
this.speed.set(speed);
camera = new OrthographicCamera(width, height);
batch = new SpriteBatch();
}
public void render(float delta){
this.camera.position.add(speed.x*delta,speed.y*delta, 0);
for(ParallaxLayer layer:layers){
batch.setProjectionMatrix(camera.projection);
batch.begin();
float currentX = - camera.position.x*layer.parallaxRatio.x % ( layer.region.getRegionWidth() + layer.padding.x) ;
if( speed.x < 0 )currentX += -( layer.region.getRegionWidth() + layer.padding.x);
do{
float currentY = - camera.position.y*layer.parallaxRatio.y % ( layer.region.getRegionHeight() + layer.padding.y) ;
if( speed.y < 0 )currentY += - (layer.region.getRegionHeight()+layer.padding.y);
do{
batch.draw(layer.region,
-this.camera.viewportWidth/2+currentX + layer.startPosition.x ,
-this.camera.viewportHeight/2 + currentY +layer.startPosition.y);
currentY += ( layer.region.getRegionHeight() + layer.padding.y );
}while( currentY < camera.viewportHeight);
currentX += ( layer.region.getRegionWidth()+ layer.padding.x);
}while( currentX < camera.viewportWidth);
batch.end();
}
}
}
You can copy/paste these classes into your project. Then, to use, do something like this:
ParallaxBackground background = new ParallaxBackground(new ParallaxLayer[]{
new ParallaxLayer(textureRegion, new Vector2(1, 1), new Vector2(0, 0)),
}, 1080, 720, new Vector2(50, 0));
Then do background.render(delta)
in your render()
method.
You can add more layers to the ParallaxBackground
constructor to fit your needs.