How to center a custom viewport?

Godot Version



I’m learning Godot by making an Asteroids clone. My viewport needs to have a set aspect ratio. This was easy enough to do by setting Stretch.Mode=viewport and Stretch.Aspect=keep. I then set the default clear color to black for the space background. However, the letterboxes added by Godot are the same color as my game background, which makes the gameplay a little confusing since it’s unclear where the edges of the map are. I didn’t find a way to change the color of the letterboxes.

To solve this, I’m using a custom viewport set to the size/aspect ratio I need, and running the game inside of it. I added a “Background” Node2D which I use to draw a black rectangle covering the viewport size, and I set the default clear color back to the default gray. This is working pretty well, but so far I haven’t been able to figure out how to center my viewport in the window. I want the aspect ratio to stay the same, but for my inner viewport to stretch until either the width or the height hits the window, while remaining centered. I’ve fiddle with various incantations of ViewportContainer, HBoxContainer, and CenterContainer with no luck so far.

Any ideas?

What ended up working for me was setting both the display size and my viewport size to the desired resolution (1024x768), then using the layout tool to center my ViewportContainer which holds the viewport.