How do I dynamically change the render aspect ratio?

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

Using the helpful tutorial at https://docs.godotengine.org/en/stable/tutorials/viewports/multiple_resolutions.html, I successfully made my game render at 1080p no matter the window size. (It has stretch_mode = 2d and strecth_aspect = keep). I can change the values in the project settings dialog and indeed the aspect ratio changes.

However, I’d like to allow the user to pick an aspect ratio at runtime. I tried changing the root viewport size (which didn’t work the way I expected), but then realized that there was a way to change the project settings dynmically.

I can call the ProjectSettings class ( ProjectSettings — Godot Engine (stable) documentation in English ) and use set_setting on the base size ("display/window/size/width" and "display/window/size/height"), but the rendering does not change. Calls to get_setting show that in fact, the setting is set.

Is there something I am missing or is this an engine bug? If I’m missing something, how do I properly change the aspect ratio at runtime.

:bust_in_silhouette: Reply From: Calinou

To support multiple aspect ratios, set the stretch aspect to expand instead of keep. Then configure your UI nodes to have correct anchors (otherwise, UI elements will be at the wrong location when the aspect ratio changes).

:bust_in_silhouette: Reply From: RitzyMage

So after some expirementation, I found that calling

GetTree().SetScreenStretch(SceneTree.StretchMode.Mode2d, SceneTree.StretchAspect.Expand, aspectRatioSize);
    GetTree().SetScreenStretch(SceneTree.StretchMode.Mode2d, SceneTree.StretchAspect.Keep, aspectRatioSize);

(I’m using C#, but this should translate to GDScript pretty nicely) caused the changes to be applied and allowed the user to select the render resolution at runtime.