Hi all!
This is the follow-up of a previous post about scrolling.
In this case, we are going to talk about parallax scrolling. This technique provides greater realism as it simulates some feeling of depth. To understand it, think when you're in a car and you look out the window. Obviously the closest objects (e.g. the stripes of the the road) move far much faster than the objects in the horizon (e.g. the mountains or clouds).
The way you can implement this is pretty straightforward. Look at Figure 1.
Figure 1.- Parallax Scrolling: layers and objects. The closest layer (the fastest one) is the one of the palms and floor. The furthest layer (i.e. the slowest one) is the one with the moon.
Level::createLevel() {
Mountain* m = new Mountain("mountain.png");
Cloud* farCloud = new Cloud("cloud.png");
Cloud* closeCloud = new Cloud("cloud.png");
Platform* p = new Platform("platform.png");
//velocityFarLayer < velocityMidLayer < velocityCloseLayer
Layer* farLayer = new Layer(velocityFarLayer);
farLayer -> addObject(farCloud);
farLayer -> addObject(m);
Layer* midLayer = new Layer(velocityMidLayer);
midLayer -> addObject(closeCloud);
Layer* closeLayer = new Layer(velocityCloseLayer);
closeLayer -> addObject(p);
}
Level::update() {
for (Layer *l: layersInLevel) {
l -> update();
}
}
Layer::update() {
for (Object *o: objectsInLayer) {
//Each object knows how to update itself in response to physics or input
o -> update();
}
//We move the layer too
this -> move (layerVelocity);
}
Layer::move(Vector &velocity) {
for (Object *o: objectsInLayer) {
o -> move (velocity);
}
}
I think that the code is more or less self-explanatory. A level is composed of layers, each of which has a different velocity. Each layer, in turn, is composed of objects. When you design a level, you first specify the number of layers and each layer velocity. Then, you associate each object to a level. When the level is updated, each layer is updated, which means that each object in the layer will be updated and moved according to the layer velocity.
Well, that's all for now. Hope you find this information useful. Don't hesitate to leave comments or suggestions or questions.
See you!