How to center sprite and label with varying width

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Diet Estus

I have a “Notification” scene consisting of a Container node and two children: a Sprite node and a Label node.

There is a manual init() method for this scene that I call when I instance the scene. This init() method takes a string as argument and passes it into the Label.

After I call the init() method, I add the scene as a child of my “HUD” node, which is itself just a Container.

What I want is for the Sprite to always appear directly to the left of the Label, and for them both to be centered on my screen. If the text of the label is long, I want the label to stretch but still be centered. This will push the Sprite left.

For example, I want to be able to accommodate both of these:

enter image description here
enter image description here

(The red square is the Sprite, the gray rectangle is the Label.)

I have tried about every container hierarchy and anchor combination that I can think of, but just can’t seem to get it to work.

Any ideas?

:bust_in_silhouette: Reply From: volzhs

Try this.

- HBoxContainer (alignment : center)
    - TextureRect
    - Label

It’s better to use only Control nodes to consist UI instead of mixing Control & Node2D nodes.

I wasn’t familiar with TextureRect. Works like a charm!

Diet Estus | 2018-04-26 13:19

1 Like