Autoresize background image to mobile screen size

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

Haven’t messed around with this much but there is a section in the docs on dealing with multiple resolutions:
Multiple resolutions — Godot Engine (stable) documentation in English

1 Like

Thank you very much, @fireside, I´ll read that. Also, I found what it seems to be a way to deal with this, which is a TextureRect node.

1 Like