How do I center a GridContainer so that it's at the center of the screen?

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

I have a grid container that contains a number of TextureButtons. All I want to do is make it so that the it’s in the center of the screen, with an equal amount of space on the left and right sides. I’ve found similar questions asked here, but I just don’t understand.

:bust_in_silhouette: Reply From: Oen44

I hate how Node2D is scaling child nodes…
Create Node2D inside root Node2D, to new created Node2D attach GridContainer and then insert script (to Node2D), should look like this:

  • Node2D (root)
- Node2D

   - GridContainer

extends Node2D

func _ready():
	var viewport_size = get_viewport_rect().size
	var grid = get_node("GridContainer") # change name to your GridContainer
	global_position = Vector2(
		viewport_size.x / 2 - grid.rect_size.x / 4,
		viewport_size.y / 2 - grid.rect_size.y / 4
	)
	pass

#Edit
Check Xrayez answer, that should work better for you. Using my way you could make it centered if you add stuff to GridContainer in real-time and its size will change.

:bust_in_silhouette: Reply From: Xrayez

In order to center your GridContainer relative to the viewport:

  1. Select your GridContainer node.
  2. Press Layout button (resides on the toolbar above scene’s viewport)
  3. From the popup menu, select Center

If you want your TextureButtons to be centered relative to GridContainer as well:

  1. Select your TextureButton node.
  2. In the inspector, go to ControlSize flags.
  3. Enable Horizontal Expand and Horizontal Shrink Center.

I recommend going through this tutorial, it helped me a lot:

Design interfaces with the Control nodes

Yeah… I went way too far by using script.

Oen44 | 2018-09-21 12:32

Ok, this works if the root of my scene is a control node. I guess that was the problem (my root node was a Node2D and the GridContainer was being centered at the origin). Just adding this in case anyone else has the same problem. Thx!

Socrates | 2018-09-21 15:54