Up to date

This page is up to date for Godot 4.2. If you still find outdated information, please open an issue.

Преобразование области просмотра и холста

Введение

Это обзор 2D преобразований, происходящих для узлов с момента их локального рисования содержимого до момента их рисования на экране. В этом обзоре обсуждаются детали движка очень низкого уровня.

The goal of this tutorial is to teach a way for feeding input events to the Input with a position in the correct coordinate system.

A more extensive description of all coordinate systems and 2d transforms is available in 2D coordinate systems and 2D transforms.

Преобразования холста

Как упоминалось в предыдущем руководстве Слои холста, каждый узел CanvasItem (помните, что узлы на основе Node2D и Control используют CanvasItem в качестве общего корня) будет находиться в Canvas Layer. Каждый слой холста имеет преобразование (перемещение, поворот, масштаб и т.д.), к которому можно получить доступ как Transform2D.

Как было сказано в предыдущем уроке, узлы по умолчанию рисуются на 0-ом слое на встроенном холсте. Для того, чтобы поместить узлы на другой слой, можно воспользоваться узлом CanvasLayer.

Глобальное преобразование холста

Viewports also have a Global Canvas transform (also a Transform2D). This is the master transform and affects all individual Canvas Layer transforms. Generally, this is primarily used in Godot's CanvasItem Editor.

Преобразования растяжения

Наконец, в видовых экранах есть функция Stretch Transform, которая используется при изменении размера или растягивании экрана. Это преобразование используется внутренне (как описано в Multiple resolutions), но также может быть вручную установлено для каждого видового экрана.

Input events are multiplied by this transform but lack the ones above. To convert InputEvent coordinates to local CanvasItem coordinates, the CanvasItem.make_input_local() function was added for convenience.

Window transform

The root viewport is a Window. In order to scale and position the Window's content as described in Multiple resolutions, each Window contains a window transform. It is for example responsible for the black bars at the Window's sides so that the Viewport is displayed with a fixed aspect ratio.

Порядок преобразований

To convert a CanvasItem local coordinate to an actual screen coordinate, the following chain of transforms must be applied:

../../_images/viewport_transforms3.webp

Функции преобразования

The above graphic shows some available transform functions. All transforms are directed from right to left, this means multiplying a transform with a coordinate results in a coordinate system further to the left, multiplying the affine inverse of a transform results in a coordinate system further to the right:

# Called from a CanvasItem.
canvas_pos = get_global_transform() * local_pos
local_pos = get_global_transform().affine_inverse() * canvas_pos

Наконец, чтобы преобразовать локальные координаты CanvasItem в экранные координаты, просто умножьте в следующем порядке:

var screen_coord = get_viewport().get_screen_transform() * get_global_transform_with_canvas() * local_pos

Однако имейте в виду, что обычно нежелательно работать с экранными координатами. Рекомендуемый подход - просто работать в координатах холста (CanvasItem.get_global_transform ()), чтобы автоматическое изменение размера разрешения экрана работало правильно.

Передача пользовательских событий ввода

It is often desired to feed custom input events to the game. With the above knowledge, to correctly do this in the focused window, it must be done the following way:

var local_pos = Vector2(10, 20) # Local to Control/Node2D.
var ie = InputEventMouseButton.new()
ie.button_index = MOUSE_BUTTON_LEFT
ie.position = get_viewport().get_screen_transform() * get_global_transform_with_canvas() * local_pos
Input.parse_input_event(ie)