Skip to content

Instantly share code, notes, and snippets.

@rzuf79
Created April 4, 2022 08:14
Show Gist options
  • Save rzuf79/7fb464c99061a8f95b778af3a1c7c0b2 to your computer and use it in GitHub Desktop.
Save rzuf79/7fb464c99061a8f95b778af3a1c7c0b2 to your computer and use it in GitHub Desktop.
Viewport scaling for Godot
extends Node2D
"""
Viewport scaling for Godot
It's supposed to work similar to Unity's CanvasScaler set to
"Match Width or Height"
It's best to add to stick this to an autoloaded node.
"""
export(float, 0.0, 1.0) var width_height_factor = 0.5
var _default_size = Vector2.ZERO
func _ready():
_default_size.x = ProjectSettings.get_setting("display/window/size/width")
_default_size.y = ProjectSettings.get_setting("display/window/size/height")
get_tree().connect("screen_resized", self, "_update_viewport_size")
_update_viewport_size()
func _exit_tree():
get_tree().disconnect("screen_resized", self, "_update_viewport_size")
func _update_viewport_size():
var size_ratio = get_viewport_rect().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_viewport().set_size_override(true, get_viewport_rect().size / v_scale)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment