Using Anchor Positioning in Godot

Anchors are one of the ways to position Control nodes in Godot to get automatic alignment with various screen sizes. They determine the position of the corners of the Control’s rectangle in relation to its parent nodes rectangular area. But it only works if the parent node is a Viewport or a Control node.

The slider value is adjusted between 0 and 1 moving its anchor point from left-right or top-bottom of the rectangular area of the parent, and pushing the corresponding anchor point if it hits it.

Godot Anchors

In the above example, the Control node is a child of the root so its anchor points (in green) are in relation to the extents of the viewport (purple).

In this example, the Control node had a position and size already set before the anchor points were moved by adjusting the sliders. So, the top-left corner of the Control’s rectangle is offset from the top left anchor point.

This situation may lead to confusion when positioning with anchor points. You can set the rectangle position to zero (by clicking on the curved arrow) before adjusting the anchors.

As the anchor points are moved, the rectangle size will be changed to maintain the offsets between the corners of the rectangle and the anchor points.

Notice that we have a Button as a child node of the Control node. This is aligned by its top-left corner. So, if you are using the Control node to center the button on the screen, it doesn’t quite work, and the button needs to be shifted according to its rectangular size.

The anchors only work to move it to the right and down within the parent rectangular area. So the rectangle position needs to be adjusted negatively to move it left and up. If the text dynamically changes during game play, you want to make sure that the button is wide enough to avoid it expanding to the right and moving off center.

In this case, it’s problematic to assign rectangular size to the control node, so we should reset it to zero.

If you make a Control node a child of a Node2D, you will notice that its anchor controls have no effect on its position.

So hopefully you now understand how anchors are used and the potential pitfalls. Also, I highly recommend setting up your own experimental scene to play around with anchors to get a solid understanding of how they behave.

Where we have several Controls such as Buttons and Text Labels requiring automatic alignment in the scene, it’s a better idea to use Size Flags and the various Container Nodes which we will look at in UI Layout using Containers in Godot.

Comments Forum

More solutions