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:
|public class PlayState extends FlxState|
|private var hud:FlxGroup;|
|private var world:FlxTilemap;|
|private var player:PlayerSprite;|
|// Add additional variables|
|public function PlayState()|
|override public function create():void|
|// Add instantiation of variables|
|FlxG.worldBounds = new FlxRect(0, 0, world.width, world.height);|
|FlxG.camera.setBounds(0, 32, world.width, world.height, true);|
|player.cameras = new Array(FlxG.camera);|
|var hudCamera:FlxCamera = new FlxCamera(0, 0, FlxG.width, 32, 0);|
|hud = new FlxGroup();|
|// Add all HUD elements like a background or text details|
|hud.setAll("cameras", new Array(hudCamera), true);|
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.