Godot’s solution to adapt based on screen orientation and window size

Project settings

Set project settings (project.godot)->General->Display->Window->Orientation (i.e. attribute: display/window/handheld/orientation) to "sensor".
display/window/handheld/orientation

GDScript processing

func set_camera(var half_width: float, var half_height: float):
	var v = OS.get_window_size()
	if half_width >= half_height * v.aspect():
		$Camera.set_keep_aspect_mode(Camera.KEEP_WIDTH)
		$Camera.translation.y = ceil(half_width / tan($Camera.fov / 360 * PI))
	else:
		$Camera.set_keep_aspect_mode(Camera.KEEP_HEIGHT)
		$Camera.translation.y = ceil(half_height / tan($Camera.fov / 360 * PI))

func reorient_landscape():
	# set landscape layout here
	var half_w = ...
	var half_h = ...
	set_camera(half_w, half_h)

func reorient_portrait():
	# set portrait layout here
	var half_w = ...
	var half_h = ...
	set_camera(half_w, half_h)

func on_screen_resized():
	var size = OS.get_window_size()
	if size.x >= size.y:
		reorient_landscape()
	else:
		reorient_portrait()

func _ready():
	call_deferred("on_screen_resized")
	get_tree().connect("screen_resized", self, "on_screen_resized")

illustrate

  • You can adjust it according to the screen orientation (actually according to the window size) in the functions reorient_landscape () and reorient_portrait ().
  • The function on_screen_resized () is actively triggered in function _ready () to initialize the layout according to the window size.
  • The function set_camera () is used to set the lock axis and height value of the camera so that the window can completely display a rectangle with a size of (half_width * 2, half_height * 2) centered on the origin on the y=0 plane in the 3D scene (project settings The stretch properties of the middle window are mode=disabled, shrink=1).
  • Changing the window size to display horizontally or vertically on the PC version is also effective.

reference

Godot Multi-resolution
Godot API - OS
Godot API - SceneTree

Guess you like

Origin blog.csdn.net/feiyunw/article/details/127605589