Managing Multiple Layers
As different types of layers are introduced to a game, your ability to manage how those layers interact becomes important, especially when you need to move them in front and behind one another. The LayerManager
provides a way to manage the z-order (order of which layers from front to back). Using the fish example, you may want the fish to swim behind the scenery rather than through it. Introducing a LayerManager
allows you to achieve this with a few lines of code.
First, create the LayerManager and add the background and fish layers to the manager. The order in which you add the layers is important because it determines the z-order. The first item you add (in this case the background) is the closest to the user. The second item you add (the fish) is the furthest from the user, causing the fish to swim behind the scenery when the two layers come to occupy the same physical space.
LayerManager manager = new LayerManager();
In order for the LayerManager to be successful in managing the z-order, it calls the LayerManager.paint()
method instead of the individual Sprite
and TiledLayer paint()
methods. The LayerManager
then calls each layer's paint()
method in the proper order. To enhance the fish example, clear the screen and call the manager's paint()
manager.paint(getGraphics(), 0, 0);
Note that an x, y coordinate is also specified in LayerManager.paint()
method. This allows the location of the paint context to change relative to the screen. In this example, the coordinates of the LayerManager
and the screen are set to be equal.
Greater Rendering Flexibility
MIDP 2.0 offers flexibility in rendering visual elements to the screen. This is critical to ensure smooth performance for games. Since objects such as Sprite and TiledLayer perform the actual rendering at a lower level, the performance is much better than if the same operations were implemented in Java code within the application. The bottom line is Layer and GameCanvas provide fine-grained control over the user interface while making image rendering easier and efficient.