Godot Version
4.2.2
Question
Hello everyone, after several hours trying to solve this, I’m consulting here to see if someone can guide me (I’m a beginner in Godot, I’ve only been testing the engine for a couple of days).
The root of my scene is a node, which has a script, and a child node that is a Sprite2D with a texture of 324 x 576 pixels (a background that should always cover the screen of the Android mobile on which it runs, without leaving black bars or empty spaces, no matter what the size or aspect ratio of the screen is).
The size of the viewport is also 324 x 576.
I started developing this script, which compares the aspect ratio of the background image versus the aspect ratio of the viewport, and depending on whether it is smaller or larger than the latter, it should enlarge the image. But in all the tests I do, as soon as I modify the aspect ratio of the viewport, the image of the Sprite2D simply disappears. If anyone knows what I’m doing wrong, I would greatly appreciate it!
extends Node
@onready var sprite = $Test324x576
var bgWidth: float
var bgHeight: float
var arBackground: float
var viewportSize
var arViewport: float
var viewportSizeX: float
var viewportSizeY: float
func _ready():
# Calculate the sprite aspect ratio
bgWidth = sprite.texture.get_width()
bgHeight = sprite.texture.get_height()
arBackground = bgWidth / bgHeight
func _process(_delta):
viewportSize = get_viewport().size
viewportSizeX = viewportSize.x
viewportSizeY = viewportSize.y
arViewport = viewportSizeX / viewportSizeY
if arViewport > arBackground:
sprite.scale.x = bgAncho / arViewport
sprite.scale.y = bgAlto / arViewport
# After modifying the aspect ratio of the viewport in real time, sprite instantly
# dissapeared from screen