Attention: Here be dragons
This is the latest
(unstable) version of this documentation, which may document features
not available in or compatible with released stable versions of Godot.
Checking the stable version of the documentation...
Input
Успадковує: Object
Однотон для введення даних.
Опис
Input однотонні ручки клавішні преси, кнопки миші і рух, ігрові блоки і вхідні дії. Дії та події можуть бути встановлені в вкладці ** Вхідна карта ** Проект > Параметри проекту, або з класом InputMap.
Примітка: Input методи відображають глобальний вхідний стан і не впливають на управління.accept_event() або Viewport.set_input_as_handled(), оскільки ці методи мають справу з введенням способу пропаговано в SceneTree.
Посібники
Властивості
Методи
void |
action_press(action: StringName, strength: float = 1.0) |
void |
action_release(action: StringName) |
void |
add_joy_mapping(mapping: String, update_existing: bool = false) |
void |
clear_joy_motion_sensors_calibration(device: int) |
void |
|
Vector3 |
get_accelerometer() const |
get_action_raw_strength(action: StringName, exact_match: bool = false) const |
|
get_action_strength(action: StringName, exact_match: bool = false) const |
|
get_axis(negative_action: StringName, positive_action: StringName) const |
|
get_current_cursor_shape() const |
|
Vector3 |
get_gravity() const |
Vector3 |
get_gyroscope() const |
Vector3 |
get_joy_accelerometer(device: int) const |
get_joy_axis(device: int, axis: JoyAxis) const |
|
Vector3 |
get_joy_gravity(device: int) const |
String |
get_joy_guid(device: int) const |
Vector3 |
get_joy_gyroscope(device: int) const |
get_joy_info(device: int) const |
|
get_joy_motion_sensors_calibration(device: int) const |
|
get_joy_motion_sensors_rate(device: int) const |
|
String |
get_joy_name(device: int) |
get_joy_vibration_duration(device: int) |
|
get_joy_vibration_remaining_duration(device: int) |
|
Vector2 |
get_joy_vibration_strength(device: int) |
Vector2 |
|
Vector2 |
|
Vector3 |
get_magnetometer() const |
BitField[MouseButtonMask] |
get_mouse_button_mask() const |
Vector2 |
get_vector(negative_x: StringName, positive_x: StringName, negative_y: StringName, positive_y: StringName, deadzone: float = -1.0) const |
has_joy_light(device: int) const |
|
has_joy_motion_sensors(device: int) const |
|
has_joy_vibration(device: int) const |
|
is_action_just_pressed(action: StringName, exact_match: bool = false) const |
|
is_action_just_pressed_by_event(action: StringName, event: InputEvent, exact_match: bool = false) const |
|
is_action_just_released(action: StringName, exact_match: bool = false) const |
|
is_action_just_released_by_event(action: StringName, event: InputEvent, exact_match: bool = false) const |
|
is_action_pressed(action: StringName, exact_match: bool = false) const |
|
is_anything_pressed() const |
|
is_joy_button_pressed(device: int, button: JoyButton) const |
|
is_joy_known(device: int) |
|
is_joy_motion_sensors_calibrated(device: int) const |
|
is_joy_motion_sensors_calibrating(device: int) const |
|
is_joy_motion_sensors_enabled(device: int) const |
|
is_joy_vibrating(device: int) |
|
is_key_label_pressed(keycode: Key) const |
|
is_key_pressed(keycode: Key) const |
|
is_mouse_button_pressed(button: MouseButton) const |
|
is_physical_key_pressed(keycode: Key) const |
|
void |
parse_input_event(event: InputEvent) |
void |
remove_joy_mapping(guid: String) |
void |
set_accelerometer(value: Vector3) |
void |
set_custom_mouse_cursor(image: Resource, shape: CursorShape = 0, hotspot: Vector2 = Vector2(0, 0)) |
void |
set_default_cursor_shape(shape: CursorShape = 0) |
void |
set_gravity(value: Vector3) |
void |
set_gyroscope(value: Vector3) |
void |
set_joy_light(device: int, color: Color) |
void |
set_joy_motion_sensors_calibration(device: int, calibration_info: Dictionary) |
void |
set_joy_motion_sensors_enabled(device: int, enable: bool) |
void |
set_magnetometer(value: Vector3) |
should_ignore_device(vendor_id: int, product_id: int) const |
|
void |
start_joy_motion_sensors_calibration(device: int) |
void |
start_joy_vibration(device: int, weak_magnitude: float, strong_magnitude: float, duration: float = 0) |
void |
stop_joy_motion_sensors_calibration(device: int) |
void |
stop_joy_vibration(device: int) |
void |
vibrate_handheld(duration_ms: int = 500, amplitude: float = -1.0) |
void |
warp_mouse(position: Vector2) |
Сигнали
joy_connection_changed(device: int, connected: bool) 🔗
Випробувано, коли підключено пристрій Hotpad.
Переліки
enum MouseMode: 🔗
MouseMode MOUSE_MODE_VISIBLE = 0
Зробіть курсор мишки видимим, якщо він прихований.
Зробіть курсор миші, прихований, якщо це видно.
MouseMode MOUSE_MODE_CAPTURED = 2
Захоплює мишу. Миша буде прихована і її позиція закривається в центрі вікна менеджера.
Примітка: Якщо ви хочете обробити рух мишки в цьому режимі, вам потрібно скористатися InputEventMouseMotion.relative.
MouseMode MOUSE_MODE_CONFINED = 3
Налаштуйте курсор миші на ігровому вікні, і зробіть його видимими.
Налаштуйте курсор миші на ігровому вікні, і зробіть його прихованим.
MouseMode MOUSE_MODE_MAX = 5
Максимальне значення MouseMode.
enum CursorShape: 🔗
CursorShape CURSOR_ARROW = 0
Перевірити курсор. Стандарт, курсор за замовчуванням.
CursorShape CURSOR_IBEAM = 1
I-beam курсор. Зазвичай використовується для відображення, коли натискається курсор тексту.
CursorShape CURSOR_POINTING_HAND = 2
Точка ручного курсора. Зазвичай використовується для позначення тостера за посиланням або іншим взаємодієним елементом.
CursorShape CURSOR_CROSS = 3
Перетин курсора. Зазвичай з'являється над регіонами, в яких може бути виконана робота малюнка або підбір.
CursorShape CURSOR_WAIT = 4
Зачекайте курсор. Повідомляє, що додаток зайнятий, що не можна використовувати під час операції (наприклад, щось блокує основну нитку).
CursorShape CURSOR_BUSY = 5
Автобусний курсор. Повідомляє, що додаток зайнято, і це все ще можна при експлуатації.
CursorShape CURSOR_DRAG = 6
Перетягніть курсор. Зазвичай відображається при перетягування щось.
Примітка: Windows не вистачає курсора, тому CURSOR_DRAG є таким же, як CURSOR_MOVE для цієї платформи.
CursorShape CURSOR_CAN_DROP = 7
Може падіння курсора. Як правило, відображається при перетягування щось, щоб вказати, що він може бути скиданий на поточному положенні.
CursorShape CURSOR_FORBIDDEN = 8
Заборонений курсор. Повідомляє, що поточна дія заборонена (наприклад, при перетягування щось) або що контроль на позиції вимкнено.
CursorShape CURSOR_VSIZE = 9
Вертикальний кратний курс миші. Двоголова вертикальна стрілка. Розповідає користувачу можливість змінити вікно або панель вертикально.
CursorShape CURSOR_HSIZE = 10
Горизонтальний розмір мишки курсор. Двоголова горизонтальна стрілка. Розповідає користувачу можливість змінити вікно або панель горизонтально.
CursorShape CURSOR_BDIAGSIZE = 11
Вікно змініть курсор мишки. Екскурсор - двоголова стрілка, яка йде знизу зліва на верхню праву. Розповідає користувачу можливість змінити вікно або панель як горизонтально, так і вертикально.
CursorShape CURSOR_FDIAGSIZE = 12
Вікно змініть курсор мишки. Екскурсор - двоголова стрілка, яка йде з верхньої частини, зліва на низ, протилежна CURSOR_BDIAGSIZE. Розповідає користувачу можливість змінити вікно або панель як горизонтально, так і вертикально.
CursorShape CURSOR_MOVE = 13
Перемістити курсор. Повідомляє, що щось можна перенести.
CursorShape CURSOR_VSPLIT = 14
Вертикальний спліт курсор миші. На Windows, це так само, як CURSOR_VSIZE.
CursorShape CURSOR_HSPLIT = 15
Горизонтальний курсор мишки. На Windows, це те ж саме, як CURSOR_HSIZE.
CursorShape CURSOR_HELP = 16
Довідка курсора. Зазвичай знак питання.
Описи властивостей
bool emulate_mouse_from_touch 🔗
Якщо true, надсилайте події введення мишки при натисканні або закручуванні на сенсорному екрані. Дивись також ProjectSettings.input_devices/pointing/emulate_mouse_from_touch.
bool emulate_touch_from_mouse 🔗
Якщо true, надсилайте сенсорні вхідні події при натисканні або перетягування миші. Дивись також ProjectSettings.input_devices/pointing/emulate_touch_from_mouse.
bool ignore_joypad_on_unfocused_application 🔗
void set_ignore_joypad_on_unfocused_application(value: bool)
bool is_ignoring_joypad_on_unfocused_application()
If true, joypad input (including motion sensors) and LED light changes will be ignored and joypad vibration will be stopped when the application is not focused.
Керує режимом миші.
Якщо true, скупчуються аналогічні вхідні події, надіслані операційною системою. Коли ввімкнено накопичення, всі вхідні події, що створюються під час рами, будуть об'єднані і введені при виконанні рами. Таким чином, це обмежує кількість вхідних методових дзвінків за секунду до рендерингу FPS.
Скупчення введення може бути вимкнено, щоб отримати трохи більш точний/реактивний вхід за вартістю збільшення використання процесора. У додатках, де потрібно малювати вільні лінії, вводне накопичення повинно бути відключено, поки користувач є кресленням лінії, щоб отримати результати, які уважно слідують фактичному вводі.
Note: Скупчення входу enabled за замовчуванням.
Описи методів
void action_press(action: StringName, strength: float = 1.0) 🔗
Це імітує пресування зазначеної дії.
Міцність може бути використана для небололевих дій, вона коливається між 0 і 1, що представляє інтенсивність даної дії.
Примітка: Цей метод не викликає ніяких Node._input() дзвінків. Призначений для використання _action_pressed() і _action_just_pressed(). Якщо ви хочете імітувати _input, скористайтеся parse_input_event() замість.
void action_release(action: StringName) 🔗
Якщо зазначена дія вже пресована, це випустить її.
void add_joy_mapping(mapping: String, update_existing: bool = false) 🔗
Додавання нового запису картування (в форматі SDL2) до бази даних картування. Додатково оновлення вже підключених пристроїв.
void clear_joy_motion_sensors_calibration(device: int) 🔗
Експериментальний: Цей метод може бути змінений або усунутий у наступних версіях.
Clears the calibration information for the specified joypad's motion sensors, if it has any and if they were calibrated.
See start_joy_motion_sensors_calibration() for an example on how to use joypad motion sensors and calibration in your games.
Note: This feature is only supported on Windows, Linux, macOS, and iOS.
void flush_buffered_events() 🔗
Відправляє всі вхідні події, які знаходяться в поточному буфері до ігрової петлі. Ці події можуть бути відправлені в результаті накопичення вводу (use_accumulated_input) або поглинання вводу (ProjectSettings.input_devices/buffering/agile_event_flushing).
Двигун вже зробить це на ключових точках виконання (не рідше одного разу на кадр). Тим не менш, це може бути корисним у розширених випадках, коли ви хочете точний контроль над термінами обробки подій.
Vector3 get_accelerometer() const 🔗
Повертає прискорення в м/с² датчика акселерометра пристрою, якщо він є. В іншому випадку метод повертає Vector3.ZERO.
Зауважте, що цей метод повертає порожній Vector3 під час запуску з редактора, навіть якщо ваш пристрій має акселерометр. Ви повинні експортувати свій проект на підтримуваний пристрій, щоб зчитувати значення з акселерометра.
Примітка. Цей метод працює лише на Android та iOS. На інших платформах він завжди повертає Vector3.ZERO.
Примітка. Для Android потрібно ввімкнути ProjectSettings.input_devices/sensors/enable_accelerometer.
float get_action_raw_strength(action: StringName, exact_match: bool = false) const 🔗
Повертає значення між 0 і 1, що представляє собою сиру інтенсивність даної дії, ігноруючи химерну зону дії. У більшості випадків слід використовувати get_action_strength().
Якщо точний_match є false, він ігнорує додаткові модифікатори введення для InputEventKey і InputEventMouseButton події, і напрямок для InputEventJoypadMotion події.
float get_action_strength(action: StringName, exact_match: bool = false) const 🔗
Повертає значення 0 і 1, що представляє інтенсивність даної дії. У радіпаді, наприклад, далі від осі (алогові палички або L2, R2 тригери) з мертвої зони, чим ближче значення буде до 1. Якщо дія малюється на контроль, який не має осі, такі як клавіатура, значення повертається буде 0 або 1.
Якщо exact_match є false, він ігнорує додаткові модифікатори введення для InputEventKey і InputEventMouseButton події, і напрямок для InputEventJoypadMotion події.
float get_axis(negative_action: StringName, positive_action: StringName) const 🔗
Отримати вхід осі, вказавши два дії, один негативний і один позитивний.
Це швидке написання `` Input.get_action_strength("positive_action") - Input.get_action_strength("негатив_action")``.
Array[int] get_connected_joypads() 🔗
Returns an Array containing the device IDs of all currently connected joypads.
Note: The order of connected joypads can not be guaranteed to be the same after a project and/or the editor is restarted, because Godot doesn't save the order of joypad connections. Joypads are registered in the order they are discovered by Godot.
CursorShape get_current_cursor_shape() const 🔗
Повертає поточну призначену форму курсора.
Vector3 get_gravity() const 🔗
Повертає силу тяжіння в м/с² датчика акселерометра пристрою, якщо він є. В іншому випадку метод повертає Vector3.ZERO.
Примітка. Цей метод працює лише на Android та iOS. На інших платформах він завжди повертає Vector3.ZERO.
Примітка. Для Android потрібно ввімкнути ProjectSettings.input_devices/sensors/enable_gravity.
Vector3 get_gyroscope() const 🔗
Повертає швидкість обертання в рад/с навколо осей X, Y і Z пристрою датчика гіроскопа, якщо він є. В іншому випадку метод повертає Vector3.ZERO.
Примітка. Цей метод працює лише на Android та iOS. На інших платформах він завжди повертає Vector3.ZERO.
Примітка. Для Android потрібно ввімкнути ProjectSettings.input_devices/sensors/enable_gyroscope.
Vector3 get_joy_accelerometer(device: int) const 🔗
Експериментальний: Цей метод може бути змінений або усунутий у наступних версіях.
Returns the acceleration, including the force of gravity, in m/s² of the joypad's accelerometer sensor, if the joypad has one and it's currently enabled. Otherwise, the method returns Vector3.ZERO. See also get_joy_gravity() and set_joy_motion_sensors_enabled().
For a joypad held in front of you, the returned axes are defined as follows:
+X ... -X: left ... right;
+Y ... -Y: bottom ... top;
+Z ... -Z: farther ... closer.
The gravity part value is measured as a vector with length of 9.8 away from the center of the Earth, which is a negative Y value.
Note: This feature is only supported on Windows, Linux, and macOS. On iOS, joypad accelerometer sensor reading is not supported due to OS limitations.
float get_joy_axis(device: int, axis: JoyAxis) const 🔗
Повертає поточне значення осі джойстика за індексом axis.
Vector3 get_joy_gravity(device: int) const 🔗
Експериментальний: Цей метод може бути змінений або усунутий у наступних версіях.
Returns the gravity in m/s² of the joypad's accelerometer sensor, if the joypad has one and it's currently enabled. Otherwise, the method returns Vector3.ZERO. See also get_joy_accelerometer() and set_joy_motion_sensors_enabled().
For a joypad held in front of you, the returned axes are defined as follows:
+X ... -X: left ... right;
+Y ... -Y: bottom ... top;
+Z ... -Z: farther ... closer.
The gravity part value is measured as a vector with length of 9.8 away from the center of the Earth, which is a negative Y value.
Note: This feature is only supported on Windows, Linux, and macOS. On iOS, joypad accelerometer sensor reading is not supported due to OS limitations.
String get_joy_guid(device: int) const 🔗
Returns an SDL-compatible device GUID on platforms that use gamepad remapping, e.g. 030000004c050000c405000000010000. Returns an empty string if it cannot be found. Godot uses SDL's internal mappings, supplemented by community-contributed mappings, to determine gamepad names and mappings based on this GUID.
On Windows, all XInput joypad GUIDs will be overridden by Godot to __XINPUT_DEVICE__, because their mappings are the same.
Vector3 get_joy_gyroscope(device: int) const 🔗
Експериментальний: Цей метод може бути змінений або усунутий у наступних версіях.
Returns the rotation rate in rad/s around a joypad's X, Y, and Z axes of the gyroscope sensor, if the joypad has one and it's currently enabled. Otherwise, the method returns Vector3.ZERO. See also set_joy_motion_sensors_enabled().
The rotation is positive in the counter-clockwise direction.
For a joypad held in front of you, the returned axes are defined as follows:
X: Angular speed around the X axis (pitch);
Y: Angular speed around the Y axis (yaw);
Z: Angular speed around the Z axis (roll).
See start_joy_motion_sensors_calibration() for an example on how to use joypad gyroscope and gyroscope calibration in your games.
Note: This feature is only supported on Windows, Linux, macOS, and iOS.
Dictionary get_joy_info(device: int) const 🔗
Returns a dictionary with extra platform-specific information about the device, e.g. the raw gamepad name from the OS or the Steam Input index.
On Windows, Linux, macOS, and iOS, the dictionary contains the following fields:
raw_name: The name of the controller as it came from the OS, before getting renamed by the controller database.
vendor_id: The USB vendor ID of the device.
product_id: The USB product ID of the device.
serial_number: The serial number of the device. This key won't be present if the serial number is unavailable.
The dictionary can also include the following fields under selected platforms:
steam_input_index: The Steam Input gamepad index (Windows, Linux, and macOS only). If the device is not a Steam Input device this key won't be present.
xinput_index: The index of the controller in the XInput system (Windows only). This key won't be present for devices not handled by XInput.
Note: The returned dictionary is always empty on Android and Web.
Dictionary get_joy_motion_sensors_calibration(device: int) const 🔗
Експериментальний: Цей метод може бути змінений або усунутий у наступних версіях.
Returns the calibration information about the specified joypad's motion sensors in the form of a Dictionary, if it has any and if they have been calibrated, otherwise returns an empty Dictionary.
The dictionary contains the following fields:
gyroscope_offset: average offset in gyroscope values from Vector2.ZERO in rad/s.
See start_joy_motion_sensors_calibration() for an example on how to use joypad motion sensors and calibration in your games.
Note: This feature is only supported on Windows, Linux, macOS, and iOS.
float get_joy_motion_sensors_rate(device: int) const 🔗
Експериментальний: Цей метод може бути змінений або усунутий у наступних версіях.
Returns the joypad's motion sensor rate in Hz, if the joypad has motion sensors and they're currently enabled. See also set_joy_motion_sensors_enabled().
Note: This feature is only supported on Windows, Linux, macOS, and iOS.
String get_joy_name(device: int) 🔗
Повертає ім'я джойстику в зазначеному індексі пристрою, наприклад PS4 контролер. Godot використовує SDL2 бази даних ігрових контролерів для визначення назв геймпада.
float get_joy_vibration_duration(device: int) 🔗
Returns the duration of the current vibration effect in seconds.
Note: This method returns the same value that was passed to start_joy_vibration(), and this value does not change when the joypad's vibration runs out, it only gets reset after a call to stop_joy_vibration().
If you want to check if a joypad is still vibrating, use is_joy_vibrating() instead.
float get_joy_vibration_remaining_duration(device: int) 🔗
Експериментальний: Цей метод може бути змінений або усунутий у наступних версіях.
Returns the remaining duration of the current vibration effect in seconds.
Vector2 get_joy_vibration_strength(device: int) 🔗
Returns the strength of the joypad vibration: x is the strength of the weak motor, and y is the strength of the strong motor.
Note: This method returns the same values that were passed to start_joy_vibration(), and these values do not change when the joypad's vibration runs out, they only get reset after a call to stop_joy_vibration().
If you want to check if a joypad is still vibrating, use is_joy_vibrating() instead.
Vector2 get_last_mouse_screen_velocity() 🔗
Повернення останньої швидкості мишки в координатах екрана. Для забезпечення точної і безжорсткої швидкості миша обчислюється тільки кожен 0.1s. Таким чином, швидкість мишки відставить рухи миші.
Vector2 get_last_mouse_velocity() 🔗
Повернення останньої швидкості мишки. Для забезпечення точної і безжорсткої швидкості миша обчислюється тільки кожен 0.1s. Таким чином, швидкість мишки відставить рухи миші.
Vector3 get_magnetometer() const 🔗
Повертає напруженість магнітного поля в мікротеслах для всіх осей датчика магнітометра пристрою, якщо він є. В іншому випадку метод повертає Vector3.ZERO.
Примітка. Цей метод працює лише на Android та iOS. На інших платформах він завжди повертає Vector3.ZERO.
Примітка. Для Android потрібно ввімкнути ProjectSettings.input_devices/sensors/enable_magnetometer.
BitField[MouseButtonMask] get_mouse_button_mask() const 🔗
Повертаємо кнопки миші як трохи. Якщо кілька кліків мишки натискаються одночасно, укуси додаються разом. Equivalent to DisplayServer.mouse_get_button_state().
Vector2 get_vector(negative_x: StringName, positive_x: StringName, negative_y: StringName, positive_y: StringName, deadzone: float = -1.0) const 🔗
Прискорює вхідний вектор, вказавши чотири дії для позитиву і негативних X і Y-акс.
Цей метод корисний при отриманні вектора вводу, таких як з джойстику, спрямована накладка, стріли або WASD. Вектор має свою довжину, обмежену 1 і має круговий дільник, який корисний для використання векторного введення в рух.
За промовчанням, фрагмент автоматично обчислюється з середньої дії францонів. Однак, ви можете перенаречени мертвогозону, щоб бути, що ви хочете (на діапазоні 0 до 1).
bool has_joy_light(device: int) const 🔗
Returns true if the joypad has an LED light that can change colors and/or brightness. See also set_joy_light().
Note: This feature is only supported on Windows, Linux, macOS, and iOS.
bool has_joy_motion_sensors(device: int) const 🔗
Експериментальний: Цей метод може бути змінений або усунутий у наступних версіях.
Returns true if the joypad has motion sensors (accelerometer and gyroscope).
Note: On iOS, joypad accelerometer sensor reading is not supported due to OS limitations.
Note: This feature is only supported on Windows, Linux, macOS, and iOS.
bool has_joy_vibration(device: int) const 🔗
Returns true if the joypad supports vibration. See also start_joy_vibration().
Note: For macOS, vibration is only supported in macOS 11 and later. When connected via USB, vibration is only supported for major brand controllers (except Xbox One and Xbox Series X/S controllers) due to macOS limitations.
bool is_action_just_pressed(action: StringName, exact_match: bool = false) const 🔗
Повертає true, коли користувач почав натискати подію дії в поточному кадрі або фізичному тику. Повертає true тільки в кадрі або тику, в якому користувач натиснув кнопку.
Це корисно для коду, який потрібно виконати тільки один раз при натисканні дії, а не в кожному кадрі, поки вона натиснута.
Якщо exact_match дорівнює false, ігноруються додаткові модифікатори вводу для подій InputEventKey та InputEventMouseButton, а також напрямок для подій InputEventJoypadMotion.
Примітка: Повернення true не означає, що дія все ще натиснута. Дію можна швидко натиснути і відпустити, і true все одно буде повернуто, щоб не пропустити введення.
Примітка: Через ефект «привидів» клавіатури is_action_just_pressed() може повернути false, навіть якщо одна з клавіш дії натиснута. Дивіться Приклади введення в документації для отримання додаткової інформації.
Примітка: Під час обробки введення (наприклад, Node._input()), використовуйте InputEvent.is_action_pressed() для запиту стану дії поточної події. Див. також is_action_just_pressed_by_event().
bool is_action_just_pressed_by_event(action: StringName, event: InputEvent, exact_match: bool = false) const 🔗
Повертає true, коли користувач почав натискати подію дії в поточному кадрі або фізичному тику, і першою подією, яка викликала натискання дії в поточному кадрі/фізичному тику, була event. Вона поверне true тільки в кадрі або тику, в якому користувач натиснув кнопку.
Це корисно для коду, який потрібно виконати тільки один раз, коли натискається дія, і дія обробляється під час обробки вводу (наприклад, Node._input()).
Якщо exact_match дорівнює false, він ігнорує додаткові модифікатори введення для подій InputEventKey та InputEventMouseButton, а також напрямок для подій InputEventJoypadMotion.
Примітка: Повернення true не означає, що дія все ще натиснута. Дію можна швидко натиснути і відпустити, і true все одно буде повернуто, щоб не пропустити введення.
Примітка: Через ефект «привидів» клавіатури is_action_just_pressed() може повернути false, навіть якщо одна з клавіш дії натиснута. Дивіться Приклади введення в документації для отримання додаткової інформації.
bool is_action_just_released(action: StringName, exact_match: bool = false) const 🔗
Повертає true, коли користувач припиняє натискати подію дії в поточному кадрі або фізичному тику. Воно повертає true тільки в кадрі або тику, коли користувач відпускає кнопку.
Примітка: Повернення true не означає, що дія все ще не натиснута. Дія може бути швидко відпущена і натиснута знову, і true все одно буде повернуто, щоб не пропустити введення.
Якщо exact_match дорівнює false, ігноруються додаткові модифікатори введення для подій InputEventKey і InputEventMouseButton, а також напрямок для подій InputEventJoypadMotion.
Примітка: Під час обробки введення (наприклад, Node._input()), використовуйте InputEvent.is_action_released() для запиту стану дії поточної події. Див. також is_action_just_released_by_event().
bool is_action_just_released_by_event(action: StringName, event: InputEvent, exact_match: bool = false) const 🔗
Повертає true, коли користувач припиняє натискати подію дії в поточному кадрі або фізичному тику, а першою подією, яка викликала звільнення дії в поточному кадрі/фізичному тику, була event. Вона повертатиме true тільки в кадрі або тику, в якому користувач відпускає кнопку.
Це корисно, коли дія обробляється під час обробки вводу (наприклад, Node._input()).
Примітка: Повернення true не означає, що дія все ще не натиснута. Дію можна швидко відпустити і натиснути знову, і true все одно буде повернуто, щоб не пропустити ввід.
Якщо exact_match має значення false, ігноруються додаткові модифікатори введення для подій InputEventKey та InputEventMouseButton, а також напрямок для подій InputEventJoypadMotion.
bool is_action_pressed(action: StringName, exact_match: bool = false) const 🔗
Повертаємо true, якщо ви натискаємо акцію.
Якщо exact_match є false, він ігнорує додаткові модифікатори введення для InputEventKey і InputEventMouseButton події, і напрямок для InputEventJoypadMotion події.
Примітка: У зв'язку з привидами клавіатури, _action_pressed() може повернутися false навіть якщо один з ключів дії натискається. Див. Налаштування прикладів в документації для отримання додаткової інформації.
bool is_anything_pressed() const 🔗
Повертаємо true, якщо будь-яка дія, ключ, кнопка Hotpad або кнопка миша натискається. Це також повернеться true, якщо будь-яка дія змоделюється через код, зателефонувавши action_press().
bool is_joy_button_pressed(device: int, button: JoyButton) const 🔗
Returns true if you are pressing the joypad button at index button.
Note: If you want to check if a joypad button was just pressed, use Godot's input action system with is_action_just_pressed() or use the Node._input() method like this instead:
func _input(event):
if event is InputEventJoypadButton and event.is_pressed() and event.button_index == JOY_BUTTON_A:
pass # Your code here.
public override void _Input(InputEvent @event)
{
if (@event is InputEventJoypadButton eventButton && eventButton.Pressed && eventButton.ButtonIndex == JoyButton.A)
{
// Your code here.
}
}
bool is_joy_known(device: int) 🔗
Повертає true, якщо система знає зазначений пристрій. Це означає, що він встановлює всі кнопки і осі індекси. Невідомі джойстики не чекають, щоб відповідати цим константам, але ви ще можете отримати події з них.
bool is_joy_motion_sensors_calibrated(device: int) const 🔗
Експериментальний: Цей метод може бути змінений або усунутий у наступних версіях.
Returns true if the joypad's motion sensors have been calibrated.
See start_joy_motion_sensors_calibration() for an example on how to use joypad motion sensors and calibration in your games.
Note: This feature is only supported on Windows, Linux, macOS, and iOS.
bool is_joy_motion_sensors_calibrating(device: int) const 🔗
Експериментальний: Цей метод може бути змінений або усунутий у наступних версіях.
Returns true if the joypad's motion sensors are currently being calibrated.
See start_joy_motion_sensors_calibration() for an example on how to use joypad motion sensors and calibration in your games.
Note: This feature is only supported on Windows, Linux, macOS, and iOS.
bool is_joy_motion_sensors_enabled(device: int) const 🔗
Експериментальний: Цей метод може бути змінений або усунутий у наступних версіях.
Returns true if the requested joypad has motion sensors (accelerometer and gyroscope) and they are currently enabled. See also set_joy_motion_sensors_enabled() and has_joy_motion_sensors().
See start_joy_motion_sensors_calibration() for an example on how to use joypad motion sensors and calibration in your games.
Note: This feature is only supported on Windows, Linux, macOS, and iOS.
bool is_joy_vibrating(device: int) 🔗
Експериментальний: Цей метод може бути змінений або усунутий у наступних версіях.
Returns true if the joypad is still vibrating after a call to start_joy_vibration().
Unlike get_joy_vibration_strength() and get_joy_vibration_duration(), this method returns false after the joypad's vibration runs out.
bool is_key_label_pressed(keycode: Key) const 🔗
Returns true if you are pressing the key with the keycode printed on it. You can pass a Key constant or any Unicode character code.
Note: If you want to check if a key was just pressed by using its label, use Godot's input action system with is_action_just_pressed() or use the Node._input() method like this instead:
func _input(event):
if event is InputEventKey and not event.is_echo() and event.is_pressed() and event.key_label == KEY_SPACE:
pass # Your code here.
public override void _Input(InputEvent @event)
{
if (@event is InputEventKey eventKey && !eventKey.IsEcho() && eventKey.Pressed && eventKey.KeyLabel == Key.Space)
{
// Your code here.
}
}
bool is_key_pressed(keycode: Key) const 🔗
Returns true if you are pressing the Latin key in the current keyboard layout. You can pass a Key constant.
is_key_pressed() is only recommended over is_physical_key_pressed() in non-game applications. This ensures that shortcut keys behave as expected depending on the user's keyboard layout, as keyboard shortcuts are generally dependent on the keyboard layout in non-game applications. If in doubt, use is_physical_key_pressed().
Note: Due to keyboard ghosting, is_key_pressed() may return false even if one of the action's keys is pressed. See Input examples in the documentation for more information.
Note: If you want to check if a key was just pressed by using its keycode, use Godot's input action system with is_action_just_pressed() or use the Node._input() method like this instead:
func _input(event):
if event is InputEventKey and not event.is_echo() and event.is_pressed() and event.keycode == KEY_SPACE:
pass # Your code here.
public override void _Input(InputEvent @event)
{
if (@event is InputEventKey eventKey && !eventKey.IsEcho() && eventKey.Pressed && eventKey.Keycode == Key.Space)
{
// Your code here.
}
}
bool is_mouse_button_pressed(button: MouseButton) const 🔗
Returns true if you are pressing the mouse button specified with MouseButton.
Note: If you want to check if a mouse button was just pressed, use Godot's input action system with is_action_just_pressed() or use the Node._input() method like this instead:
func _input(event):
if event is InputEventMouseButton and event.is_pressed() and event.button_index == MOUSE_BUTTON_LEFT:
pass # Your code here.
public override void _Input(InputEvent @event)
{
if (@event is InputEventMouseButton eventMouseButton && eventMouseButton.Pressed && eventMouseButton.ButtonIndex == MouseButton.Left)
{
// Your code here.
}
}
bool is_physical_key_pressed(keycode: Key) const 🔗
Returns true if you are pressing the key in the physical location on the 101/102-key US QWERTY keyboard. You can pass a Key constant.
is_physical_key_pressed() is recommended over is_key_pressed() for in-game actions, as it will make W/A/S/D layouts work regardless of the user's keyboard layout. is_physical_key_pressed() will also ensure that the top row number keys work on any keyboard layout. If in doubt, use is_physical_key_pressed().
Note: Due to keyboard ghosting, is_physical_key_pressed() may return false even if one of the action's keys is pressed. See Input examples in the documentation for more information.
Note: If you want to check if a key was just pressed by using its physical keycode, use Godot's input action system with is_action_just_pressed() or use the Node._input() method like this instead:
func _input(event):
if event is InputEventKey and not event.is_echo() and event.is_pressed() and event.physical_keycode == KEY_SPACE:
pass # Your code here.
public override void _Input(InputEvent @event)
{
if (@event is InputEventKey eventKey && !eventKey.IsEcho() && eventKey.Pressed && eventKey.PhysicalKeycode == Key.Space)
{
// Your code here.
}
}
void parse_input_event(event: InputEvent) 🔗
Подає InputEvent у гру. Може використовуватися для штучного запуску подій введення з коду. Також генерує виклики Node._input().
var cancel_event = InputEventAction.new()
cancel_event.action = "ui_cancel"
cancel_event.pressed = правда
Input.parse_input_event(cancel_event)
var cancelEvent = new InputEventAction();
cancelEvent.Action = "ui_cancel";
cancelEvent.Pressed = true;
Input.ParseInputEvent(cancelEvent);
Примітка: виклик цієї функції не впливає на операційну систему. Так, наприклад, надсилання InputEventMouseMotion не перемістить курсор миші ОС у вказану позицію (натомість використовуйте warp_mouse()), а надсилання Alt/Cmd + Tab як InputEventKey не призведе до перемикання між активними вікнами.
void remove_joy_mapping(guid: String) 🔗
Видаляє всі зіставлення з внутрішньої бази даних, які відповідають заданому GUID. Усі наразі підключені джойстики, які використовують цей GUID, стануть невідповідними.
На Android Godot відображатиме внутрішнє резервне відображення.
void set_accelerometer(value: Vector3) 🔗
Налаштовує коефіцієнт прискорення акселерометра. Може використовуватися для відбілювання на пристроях без апаратного датчика, наприклад, в редакторі на ПК.
Примітка: Це значення може бути негайно переписано значенням датчика обладнання на Android та iOS.
void set_custom_mouse_cursor(image: Resource, shape: CursorShape = 0, hotspot: Vector2 = Vector2(0, 0)) 🔗
Встановлює власне зображення курсора миші, яке відображається лише у вікні гри, для заданої миші shape. Також можна вказати гарячу точку. Передавання null до параметра image скидає значення до системного курсора.
image може бути або Texture2D, або Image, а його розмір має бути меншим або рівним 256×256. Щоб уникнути проблем із рендерингом, рекомендуються розміри менші або рівні 128×128.
hotspot має бути в межах розміру image.
Примітка: AnimatedTexture не підтримуються як власні курсори миші. Якщо використовується AnimatedTexture, буде відображено лише перший кадр.
Примітка: Рекомендуються режими стиснення Lossless, Lossy або Uncompressed. Режим стиснення відеопам’яті можна використовувати, але він буде розпакований на процесорі, що означає сповільнення часу завантаження та відсутність збереження пам’яті порівняно з режимами без втрат.
Примітка: На веб-платформі максимально дозволений розмір зображення курсора становить 128×128. Зображення курсора розміром більше 32×32 також відображатимуться лише в тому випадку, якщо зображення курсора миші повністю розташоване на сторінці з міркувань безпеки.
void set_default_cursor_shape(shape: CursorShape = 0) 🔗
Налаштовує форму курсора за замовчуванням, щоб використовуватися у розділі замість CURSOR_ARROW.
Примітка: Якщо ви хочете змінити форму курсора за замовчуванням для вузлів Control, скористайтеся email protected.
Примітка: Цей метод генерує InputEventMouseMouseMouseMouseMotion для оновлення курсора відразу.
void set_gravity(value: Vector3) 🔗
Налаштовує значення ваги акселерометра. Може використовуватися для відбілювання на пристроях без апаратного датчика, наприклад, в редакторі на ПК.
Примітка: Дане значення може бути відразу переписано значення датчика обладнання на Android та iOS.
void set_gyroscope(value: Vector3) 🔗
Налаштовує значення швидкості обертання гіроскопа. Може використовуватися для відбілювання на пристроях без апаратного датчика, наприклад, в редакторі на ПК.
Примітка: Це значення може бути негайно переписано значенням датчика обладнання на Android та iOS.
void set_joy_light(device: int, color: Color) 🔗
Sets the joypad's LED light, if available, to the specified color. See also has_joy_light().
Note: There is no way to get the color of the light from a joypad. If you need to know the assigned color, store it separately.
Note: This feature is only supported on Windows, Linux, macOS, and iOS.
void set_joy_motion_sensors_calibration(device: int, calibration_info: Dictionary) 🔗
Експериментальний: Цей метод може бути змінений або усунутий у наступних версіях.
Sets the specified joypad's calibration information. See also get_joy_motion_sensors_calibration().
See start_joy_motion_sensors_calibration() for an example on how to use joypad motion sensors and calibration in your games.
Note: This feature is only supported on Windows, Linux, macOS, and iOS.
void set_joy_motion_sensors_enabled(device: int, enable: bool) 🔗
Експериментальний: Цей метод може бути змінений або усунутий у наступних версіях.
Enables or disables the motion sensors (accelerometer and gyroscope), if available, on the specified joypad.
See start_joy_motion_sensors_calibration() for an example on how to use joypad motion sensors and calibration in your games.
It's recommended to disable the motion sensors when they're no longer being used, because otherwise it might drain the controller battery faster.
Note: This feature is only supported on Windows, Linux, macOS, and iOS.
void set_magnetometer(value: Vector3) 🔗
Налаштовує значення магнітного поля датчика магнітометра. Може використовуватися для відбілювання на пристроях без апаратного датчика, наприклад, в редакторі на ПК.
Примітка: Це значення може бути негайно переписано значенням датчика обладнання на Android та iOS.
bool should_ignore_device(vendor_id: int, product_id: int) const 🔗
Запитання про те, чи слід ігнорувати вхідний пристрій або ні. Пристрої можна ігнорувати, встановлюючи змінну середовища SDL_GAMECONTROLLER_IGNORE_DEVICES. Читати ` Документація SDL <https://wiki.libsdl.org/SDL2>`__ для отримання додаткової інформації.
Примітка: Деякі 3rd party інструменти можуть сприяти списку ігноруваних пристроїв. Наприклад, SteamInput створює віртуальні пристрої з фізичних пристроїв для цілей переадресації. Щоб уникнути обробки одного пристрою введення двічі, оригінальний пристрій додається до списку ігнорування.
void start_joy_motion_sensors_calibration(device: int) 🔗
Експериментальний: Цей метод може бути змінений або усунутий у наступних версіях.
Starts the process of calibrating the specified joypad's gyroscope, if it has one.
Once a joypad's gyroscope has been calibrated correctly (e.g. laying still on a table without being rotated), get_joy_gyroscope() will return values close or equal to Vector3.ZERO when the joypad is not being rotated.
Here's an example of how to use joypad gyroscope and gyroscope calibration in your games:
const GYRO_SENSITIVITY = 10.0
func _ready():
# In this example we only use the first connected joypad (id 0).
if 0 not in Input.get_connected_joypads():
return
if not Input.has_joy_motion_sensors(0):
return
# We must enable the motion sensors before using them.
Input.set_joy_motion_sensors_enabled(0, true)
# (Tell the users here that they need to put their joypads on a flat surface and wait for confirmation.)
# Start the calibration process.
calibrate_motion()
func _process(delta):
# Only move the object if the joypad motion sensors are calibrated.
if Input.is_joy_motion_sensors_calibrated(0):
move_object(delta)
func calibrate_motion():
Input.start_joy_motion_sensors_calibration(0)
# Wait for some time.
await get_tree().create_timer(1.0).timeout
Input.stop_joy_motion_sensors_calibration(0)
# The joypad is now calibrated.
func move_object(delta):
var node: Node3D = ... # Put your node here.
var gyro := Input.get_joy_gyroscope(0)
node.rotation.x -= -gyro.y * GYRO_SENSITIVITY * delta # Use rotation around the Y axis (yaw) here.
node.rotation.y += -gyro.x * GYRO_SENSITIVITY * delta # Use rotation around the X axis (pitch) here.
private const float GyroSensitivity = 10.0;
public override void _Ready()
{
// In this example we only use the first connected joypad (id 0).
if (!Input.GetConnectedJoypads().Contains(0))
{
return;
}
if (!Input.HasJoyMotionSensors(0))
{
return;
}
// We must enable the accelerometer and the gyroscope before using them.
Input.SetJoyMotionSensorsEnabled(0, true);
// (Tell the users here that they need to put their joypads on a flat surface and wait for confirmation.)
// Start the calibration process.
CalibrateMotion();
}
public override void _Process(double delta)
{
// Only move the object if the joypad motion sensors are calibrated.
if (Input.IsJoyMotionSensorsCalibrated(0))
{
MoveObject(delta);
}
}
private async Task CalibrateMotion()
{
Input.StartJoyMotionSensorsCalibration(0);
// Wait for some time.
await ToSignal(GetTree().CreateTimer(1.0), SceneTreeTimer.SignalName.Timeout);
Input.StopJoyMotionSensorsCalibration(0);
// The joypad is now calibrated.
}
private void MoveObject(double delta)
{
Node3D node = ... ; // Put your object here.
Vector3 gyro = Input.GetJoyGyroscope(0);
Vector3 rotation = node.Rotation;
rotation.X -= -gyro.Y * GyroSensitivity * (float)delta; // Use rotation around the Y axis (yaw) here.
rotation.Y += -gyro.X * GyroSensitivity * (float)delta; // Use rotation around the X axis (pitch) here.
node.Rotation = rotation;
}
Note: Accelerometer sensor doesn't usually require calibration.
Note: This feature is only supported on Windows, Linux, macOS, and iOS.
void start_joy_vibration(device: int, weak_magnitude: float, strong_magnitude: float, duration: float = 0) 🔗
Starts to vibrate the joypad. See also has_joy_vibration() and is_joy_vibrating().
Joypads usually come with two rumble motors, a strong and a weak one.
weak_magnitude is the strength of the weak motor (between 0.0 and 1.0).
strong_magnitude is the strength of the strong motor (between 0.0 and 1.0).
duration is the duration of the effect in seconds (a duration of 0.0 will try to play the vibration as long as possible, which is about 65 seconds).
The vibration can be stopped early by calling stop_joy_vibration().
See also get_joy_vibration_strength() and get_joy_vibration_duration().
Note: For macOS, vibration is only supported in macOS 11 and later. When connected via USB, vibration is only supported for major brand controllers (except Xbox One and Xbox Series X/S controllers) due to macOS limitations.
void stop_joy_motion_sensors_calibration(device: int) 🔗
Експериментальний: Цей метод може бути змінений або усунутий у наступних версіях.
Stops the calibration process of the specified joypad's motion sensors.
See start_joy_motion_sensors_calibration() for an example on how to use joypad motion sensors and calibration in your games.
Note: This feature is only supported on Windows, Linux, macOS, and iOS.
void stop_joy_vibration(device: int) 🔗
Сприяє вібраційній раді, починаючи з _joy_vibration().
void vibrate_handheld(duration_ms: int = 500, amplitude: float = -1.0) 🔗
Vibrate the handheld device for the specified duration in milliseconds.
amplitude is the strength of the vibration, as a value between 0.0 and 1.0. If set to -1.0, the default vibration strength of the device is used.
Note: This method is implemented on Android, iOS, and Web. It has no effect on other platforms.
Note: For Android, vibrate_handheld() requires enabling the VIBRATE permission in the export preset. Otherwise, vibrate_handheld() will have no effect.
Note: For iOS, specifying the duration is only supported in iOS 13 and later.
Note: For Web, the amplitude cannot be changed.
Note: Some web browsers such as Safari and Firefox for Android do not support vibrate_handheld().
Note: Device settings such as vibration on/off, "do not disturb" mode or specific haptic feedback on/off may prevent vibrate_handheld() effects.
void warp_mouse(position: Vector2) 🔗
Налаштовує позицію мишки до вказаного вектора, наданого в пікселях і відносно походження на верхньому лівому куті в даний час зосереджений вікно управління вікон.
Миша позиція затискається на межі роздільної здатності екрана або на межі ігрового вікна, якщо MouseMode встановлюється до MOUSE_MODE_CONFINED або MOUSE_MODE_CONFINED_HIDDEN.
Примітка: Warp_mouse() підтримується тільки на Windows, macOS і Linux. Не впливає на Android, iOS та Web.