Created
November 28, 2023 10:50
-
-
Save rzuf79/a4057939443cee5e2cc881815b2727a3 to your computer and use it in GitHub Desktop.
Viewport/Canvas scaler for Godot 4
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extends Node | |
""" | |
Viewport scaling for Godot 4 | |
It's supposed to work similar to Unity's CanvasScaler set to | |
"Match Width or Height" | |
It's best to stick this to an autoloaded node. | |
""" | |
@export var enable := true | |
@export_range(0.0, 1.0) var width_height_factor = 0.5 | |
var _default_size = Vector2.ZERO | |
func _ready(): | |
if enable: | |
_default_size.x = ProjectSettings.get_setting("display/window/size/viewport_width") | |
_default_size.y = ProjectSettings.get_setting("display/window/size/viewport_height") | |
get_viewport().connect("size_changed", _update_viewport_size) | |
_update_viewport_size() | |
func _exit_tree(): | |
if enable: | |
get_tree().disconnect("size_changed", _update_viewport_size) | |
func _update_viewport_size(): | |
if enable: | |
var viewport_size = Vector2(get_viewport().size.x, get_viewport().size.y) | |
var size_ratio = viewport_size / _default_size | |
var width_weight = 1.0 - width_height_factor | |
var height_weight = width_height_factor | |
var v_scale = (size_ratio.x * width_weight) + (size_ratio.y * height_weight) | |
get_tree().root.content_scale_size = get_viewport().size / v_scale |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment