Game Development Reference
In-Depth Information
Adding parallax scrolling to the
mountains in the background
Parallax scrolling is a special scrolling technique that creates the illusion of depth in
a 2D scene. Therefore, the objects in the background move slower than the objects in
the foreground when the camera moves by.
We will now implement a parallax scrolling effect for the mountains in the
background of the game screen.
Add the following import line to the Mountains class:
import com.badlogic.gdx.math.Vector2;
After this, add the following lines of code to the same class:
public void updateScrollPosition (Vector2 camPosition) {
position.set(camPosition.x, position.y);
}
Next, make the following changes to the same class:
private void drawMountain (SpriteBatch batch, float offsetX, float
offsetY, float tintColor, float parallaxSpeedX) {
TextureRegion reg = null;
batch.setColor(tintColor, tintColor, tintColor, 1);
floatxRel = dimension.x * offsetX;
floatyRel = dimension.y * offsetY;
// mountains span the whole level
int mountainLength = 0;
mountainLength += MathUtils.ceil(0.5f
length / (2 * dimension.x) * (1 - parallaxSpeedX));
mountainLength += MathUtils.ceil(0.5f + offsetX);
for (int i = 0; i<mountainLength; i++) {
// mountain left
reg = regMountainLeft;
batch.draw(reg.getTexture(),
origin.x + xRel + position.x * parallaxSpeedX,
origin.y + yRel + position.y,
origin.x, origin.y,
dimension.x, dimension.y,
scale.x, scale.y,
rotation,
reg.getRegionX(), reg.getRegionY(),
reg.getRegionWidth(), reg.getRegionHeight(),
false, false);
 
Search WWH ::




Custom Search