Parallax with Scene2D

Objective

Shows how to create a simple parallax animation with Scene2D.

Concepts used in the code

How?

We create a class ParallaxBacground which extends Actor. That way it can be added as an actor to a stage. in oder to create the parallax effect we are going to draw the texture using the Wrapping parameter we have seen in our ImageTutorial.
To do this we overwrite the actor’s draw method defining how the actor is being rendered.
we loop through each texture and draw them, shifting them slightly faster for each layer.

Parallax class

public class ParallaxBackground extends Actor {

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

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

	private int speed;

	public ParallaxBackground(Array<Texture> textures){
		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 = srcY = 0;
		width =  Gdx.graphics.getWidth();
		heigth = Gdx.graphics.getHeight();
		scaleX = scaleY = 1;
		flipX = flipY = false;
	}

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

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

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

Now that we have created our ParallaxBackground class, we can instantiate it and add it to our stage. The object takes as parameter the Texture to be used for the parallax.
So in nutshell this gives us:

GameScreen

(...)
  Array<Texture> textures = new Array<Texture>();
  for(int i = 1; i <=6;i++){
    textures.add(new Texture(Gdx.files.internal("parallax/img"+i+".png")));
    textures.get(textures.size-1).setWrap(Texture.TextureWrap.MirroredRepeat, Texture.TextureWrap.MirroredRepeat);
  }

  ParallaxBackground parallaxBackground = new ParallaxBackground(textures);
  parallaxBackground.setSize(Gdx.graphics.getWidth(),Gdx.graphics.getHeight());
  parallaxBackground.setSpeed(1);
  stage.addActor(parallaxBackground);
(...)

Code

Full Code available for download here

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s