#Add health sprite to HBoxContainer

6 messages · Page 1 of 1 (latest)

gaunt basalt
#

What am I doing wrong here?

private PackedScene healthIconResource = (PackedScene)ResourceLoader.Load("res://prefabs/UI/healthIcon.tscn");
private HBoxContainer healthContainer;

    private void SetupHealth() {
        for (int i = 0; i < health; i++) {
            GD.Print("Create health sprite");
            var healthIcon = healthIconResource.Instantiate();
            healthContainer.AddChild(healthIcon);
        }
    }

Yet the result is only 2 icons and one of them misplaced! (see image)

hardy tartan
#

I don't think a container (control) can resize or position a Node2D-derived node like Sprite2D. Try a TextureRect.

#

Otherwise you can try making each Sprite2D a child of a basic control node.

#

In that case, the basic control node would act as a sort of positional anchor for the Sprite2D. However for the hboxcontainer to properly lay out each element, the basic control nodes will need to be given a minimum size property (or otherwise have their rects stretched to encapsulate their child sprite)

gaunt basalt
#

🤔 shouldn't the Hbox be enough to position the contents?
Oh wait, is it because the HBoxContainer doesn't layout nodes that are not control nodes?
I've added a colorRect as parent of the sprite, still doesn't do the trick...

gaunt basalt
#

I was able to get it better by making sure that the transparent colorRect had Fill and Expand set.

However, now when there are only 3 icons they look too spaced out. I've added another transparent colour rect to the end as a padding but that doesn't push things to the left.

Is there a way to force the HBoxContainer to align everything to the left? I haven't found anything like that.