How can I maintain a fixed aspect ratio when resizing a Defold game window?

Hello everyone,

I have a game configured with a resolution of 640x480. When I run it in its initial window size, everything looks correct. However, when I maximize or resize the window, the game content stretches and becomes distorted instead of maintaining its original aspect ratio.

What is the recommended way in Defold to keep a fixed aspect ratio (4:3 in this case) regardless of the window size? Ideally, I would like the game to scale correctly without stretching sprites or UI elements.

I have already verified that the game is configured to use the default display profiles, but I’m not sure if I need to use a camera, a custom render script, or another approach.

For reference, I am attaching the project’s GitHub repository as well as a few screenshots showing the issue at different window sizes. Davichobits/defold_space_ship

Any advice or examples would be greatly appreciated.

Thank you in advance!

I found this solution somewhere, when I had the same problem…

As far as I can see, there’s no setting that covers it and you have to do it in code.

I stuck this in the init function in my main.script that I have attached to to my main.collection bootloader

msg.post(“@render:”, “use_fixed_fit_projection”, { near = -1, far = 1 })

I’m a relative beginner at Defold, so apologies if this doesn’t work for you or there are better solutions!

1 Like
local DISPLAY_WIDTH = sys.get_config_int("display.width")
local DISPLAY_HEIGHT = sys.get_config_int("display.height")

function init(self)
	local initial_zoom = go.get("#camera", "orthographic_zoom")
	local display_scale = window.get_display_scale()
	window.set_listener(function(self, event, data)
		if event == window.WINDOW_EVENT_RESIZED then
			local window_width = data.width
			local window_height = data.height
			local design_width = DISPLAY_WIDTH / initial_zoom
			local design_height = DISPLAY_HEIGHT / initial_zoom

			-- max zoom: контент изначального разрешения заполнит и выйдет за границы экрана
			local zoom = math.max(window_width / design_width, window_height / design_height) / display_scale

			-- min zoom: контент изначального разрешения полностью поместится в экран
			--local zoom = math.min(window_width / design_width, window_height / design_height) / display_scale
			
			go.set("#camera", "orthographic_zoom", zoom)
		end
	end)
end
1 Like

Thank you, everyone, for your help. I managed to solve the issue by attaching a camera component to a camera.go game object and using the following script:

function init(self)
	print("CAMERA INIT")
	msg.post("#camera", "acquire_camera_focus")

	camera.set_orthographic_mode(
	"#camera",
	camera.ORTHO_MODE_AUTO_FIT
)
end
1 Like

Attach a camera component, set it to orthographic projection and orthographic mode to Fixed:

1 Like