Flixel: Use multiple cameras for a heads-up display (AS3)

It’s a pretty common problem. You want to have information displayed for the player like a character’s location, health, or what tools they are currently using. Yet, when using a top-down camera style, you risk the character the player is controlling colliding with or being drawn over the FlxGroup or FlxSprite on top of the map.

One solution, of course, is to limit the deadzone of the camera. Right before the character would run into the HUD area, the map moves instead. Before the dreaded collision, the camera pans itself.

However, this has the downside that whatever is on the edge of the map vertically will always be cut off from view by the HUD. The character will never quite get to it because of the deadzone. And at least some portion of the map will be unusable as a result.

The solution to both of these problems is to introduce a secondary camera for exclusive use for the HUD while also limiting the screen space of the primary, character-driven camera.

For example, consider the following code:

The main camera is being limited to starting at 0, 32, thus giving a 32 pixel vertical space — which can be increased if needed, of course — to add a heads-up display. In turn, the new hudCamera starts at 0,0 and extends down 32 pixels, meeting the other camera.

Whatever is added to the hud (FlxGroup) will be drawn within that camera space and not be affected by the scrolling camera that is following the character.



If making a side-scroller or using a similar game camera system, you can lock objects in screen space by limiting their scrollFactor property. All FlxObjects (and thus FlxSprites) have a scrollFactor.x and scrollFactor.y property. Setting both to 0 will lock that object on the screen. Despite being part of a set with a camera that pans, it will stay right where it was drawn initially until its x or y is changed.