HUD

To understand how heads-up display works, simply imagine that we draw something on a piece of glass and put this glass in front of a camera in a way that whenever the camera moves, the glass moves with it. This is exactly what we need to display the score.

AndEngine has a concept of camera scene, a scene that works as the glass. HUD is a special camera scene that has no background, so it is always see-through.

Have a look at the following illustration of how the HUD works. The black rectangle defines the visible portion of the scene. The HUD is the translucent rectangle. The resulting image has the text in the top-left corner. Even if the visible portion of the scene changes because of camera movement, the text will stay in the corner.

HUD

Another important feature of the HUD is that it is always drawn last. Even if we set a z-index of an entity to a lower number in the HUD than all the other entities in the scene, the HUD entity will be drawn on top of them. An entity attached to the HUD can only be covered by another entity in the HUD.

There is always only one HUD per camera. Also, a common mistake is to attach the HUD to the scene. It is possible, because in the end, the HUD is just an entity too. But in that case, we would lose all the advantages of the HUD. The correct way to use HUD is to set the HUD parameter of the camera using the following method:

HUD hud = new HUD();
camera.setHUD(hud);

Let's modify the code from the Writing Text section, where we added text and attached it to the scene. Now, we will create an HUD and attach the text to it. Change the GameScene class as follows:

private Text scoreText;

@Override
public void populate() {
  createBackground();
  createPlayer();
  createHUD();
}

private void createHUD() {
  HUD hud = new HUD();

  scoreText = new Text(16, 784, res.font, "0123456789", new TextOptions(HorizontalAlign.LEFT), vbom);
  scoreText.setAnchorCenter(0, 1);
  hud.attachChild(scoreText);

  camera.setHUD(hud);
}

This is all that is needed to attach the text to the HUD. We added a new method called createHUD() for convenience. In this method, we created a new hud object and attached the text to it. Finally, we passed our hud object to our camera.

If you want to destroy the HUD, simply call the following function:

camera.setHUD(null);

It's important to remember that the HUD is a property of the camera. When we switch to another scene, we have to remove the HUD.

Note

Any entity can be attached to the HUD.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.129.210.102