Godot Version
4.3, 4.4 beta 1
Question
I want my game to have a HUD/panel to show score-like information with options to show it as a ribbon at the top or a panel on the right. Ideally with options to use the bottom or left instead, but it doesn’t look as if that’s going to be possible.
I prefer to do as much as possible in code instead of in the scene editor, because the latter is laborious and inflexible. In hindsight I would have used the editor more from the start if I’d known how much Godot would fight back against code-centric development.
The main game scene extends Control and has a node derived from SubViewportContainer displaying the game, which is added to the tree after construction but before _ready
(I’ve also tried moving it to _ready
but it makes no difference). The HUD is added in _ready
.
If it’s a ribbon HUD it’s OK, even though that took ages to get right, because the UI layout system is so flaky. I tried designing the HUD in the editor instead, while I was struggling with that, but although it changed the behaviour it was still just as broken, so I went back to pure code.
Both types of HUD have the same base class which extends Control. In _enter_tree
the HUD base class adds this node hierarchy (where >
means ‘contains’: CanvasLayer > ColorRect > MarginContainer > BoxContainer > [HudItem]).
To implement the panel HUD on the right, I tried adding an HBoxContainer to the game screen’s top-level, with the SubViewportContainer and HUD panel in the HBoxContainer. The HUD rendered over the top of the game viewport instead of to the right of it. I wasn’t really surprised, after the struggle getting the ribbon HUD to work, and decided to try manual positioning, but that doesn’t work either. Neither offset_left
nor position
have any effect.
Getting desperate, I wondered if offsets only work if you also set anchors, so I set the HUD’s anchors preset to PRESET_TOP_LEFT (there is a reason I would prefer to use an offset than PRESET_TOP_RIGHT/RIGHT_WIDE, and the RIGHT presets don’t work either anyway). That didn’t make any difference to the HUD’s position, but then it gets really insane. If I set the preset after adding the HUD to the tree, it has no effect at all. But if I set the preset before adding it, it affects its (future) sibling - the game viewport - instead! Normally there’s a blank space on its right where the HUD should go, but setting the HUD’s anchors before adding it causes the game viewport to be stretched into that space, filling the window!
What the hell is going on?