Skip to content

Instantly share code, notes, and snippets.

@BarelyAliveMau5
Last active February 4, 2024 20:43
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BarelyAliveMau5/2ff2d83566e6db63b4f6f782ef46e2bc to your computer and use it in GitHub Desktop.
Save BarelyAliveMau5/2ff2d83566e6db63b4f6f782ef46e2bc to your computer and use it in GitHub Desktop.
Godot Engine - Screen content resizing without black-bars, nor distortions, nor content reveal
# What is this?
# This is my sample script used for a decent screen stretching mode in Godot. As
# of Godot 3.1 alpha, there are no good ways to resize the game screen without
# stretching it (thus making the image weird if you stretch it too much), or
# creating black bars on the screen borders (looks awful in my opinion), or
# letting the player see something not supposed to be seen (in this case,
# instead of showing the black bar, it zooms out)
#
# What it does?
# Basically, it doesn't let the player see anything beyond the specified
# resolution (defined as "desired_res"), and it scales the screen according to
# the aspect ratio. Also, it DOESN'T creates any black-bars or distortions, it
# keeps the player view as nice as possible (possibly restricting the screen if
# if you use the wrong window size, ie.: using desired_res=1280x800 and resizing
# the window to 800x1280 will cut half of the screen's content)
#
# Are there any examples?
# Yes, look at some games like diep.io (or this video of one of my projects:
# https://i.imgur.com/pD2HEuF.mp4) where you cannot see anything beyond a
# 1280x800 window (aspect ratio=16:10). This makes sense, because if players
# were allowed to see beyond that point, it would give an unfair advantage over
# other players.
#
# What are the requirements to make this work?
# This sample needs a Camera2D node to be used for the screen scale change
# and the project window stretch mode set to disabled, in order to function
# properly.
#
# What are the disadvantages?
# Nodes inside a CanvasLayer won't be scaled, it has to be done manually.
# I made this on Godot version 3.1, so it's not guaranteed to work on 3.0
extends Node2D
# Feel free to change this, but keep in your mind, you should also change
# the project's screen size accordially to have the proper effect.
onready var desired_res = Vector2(1280.0, 800.0) # desired resolution
# Alternatively, you can uncomment the code below to grab the desired
# resolution from a property of your godot's project:
# onready var desired_res = Vector2(
# ProjectSettings.get_setting("display/window/size/width"),
# ProjectSettings.get_setting("display/window/size/height")
# )
# I would have used const instead of onready var, but godot
# disallows that.
onready var desired_ratio = desired_res.x / desired_res.y
func _ready():
# this also works on android 7.1 when split-screen is used
get_tree().get_root().connect("size_changed",self,"resize")
func resize():
# this is needed to keep the same scale on different resolutions
var scaleTo = Vector2(desired_res.x / OS.window_size.x,
desired_res.y / OS.window_size.y)
var current_ratio = OS.window_size.x / OS.window_size.y
if current_ratio < desired_ratio: # when width is smaller
current_ratio -= (desired_ratio - 1) / desired_ratio * current_ratio
else:
current_ratio = desired_ratio / current_ratio
current_ratio = current_ratio * max(scaleTo.x, scaleTo.y)
$Camera2D.zoom = Vector2(current_ratio, current_ratio)
MIT License
Copyright (c) 2021 BarelyAliveMau5
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@tksney
Copy link

tksney commented Feb 9, 2020

Pode me dar uma ajuda, eu usei esse código e tenho uma Camera2D que segue meu personagem, e o HUD está em um CanvasLayer que está ligado a Camera2D para deslizar junto e sempre aparecer na tela. Mas como está no código os itens do CanvasLayer não redimensionam junto com todo o resto. Pode me dar uma luz de como faço para ele redimensionar? Pra ficar certinho com o novo tamanho de cada tela e no lugar correto.

@BarelyAliveMau5
Copy link
Author

Pode me dar uma ajuda, eu usei esse código e tenho uma Camera2D que segue meu personagem, e o HUD está em um CanvasLayer que está ligado a Camera2D para deslizar junto e sempre aparecer na tela. Mas como está no código os itens do CanvasLayer não redimensionam junto com todo o resto. Pode me dar uma luz de como faço para ele redimensionar? Pra ficar certinho com o novo tamanho de cada tela e no lugar correto.

Acredito que seus controles do HUD precisem ser alinhados manualmente pelo código, no caso eu diria que vc pode criar uma função que alinha os controles e então chamar essa função no final do resize

@nyanginator
Copy link

Thank you for sharing! I agree that this resizing behavior is logical and useful. What license is this gist released under? I'm thinking of making a simple plugin with it and wanted to make sure I give proper credit.

@BarelyAliveMau5
Copy link
Author

Thank you for sharing! I agree that this resizing behavior is logical and useful. What license is this gist released under? I'm thinking of making a simple plugin with it and wanted to make sure I give proper credit.

I updated the gist with the license

@nyanginator
Copy link

Thanks again, here's the plugin I came up with https://github.com/nyanginator/godot-scaling-canvas-layer. Asset library link: https://godotengine.org/asset-library/asset/997.

I'm definitely open to any suggestions, feedback, pull requests, etc. Let me know if you need me to adjust the credits also.

@BarelyAliveMau5
Copy link
Author

Thats great, thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment