Input

Inherits: Object

Un singleton que se ocupa de las entradas.

Descripción

Un singleton que se ocupa de las entradas. Esto incluye pulsaciones de teclas, botones del ratón y movimiento, joypads y acciones de entrada. Las acciones y sus eventos se pueden configurar en la pestaña Mapa de entradas en el Proyecto > Configuración del proyecto, o con la clase InputMap.

Tutoriales

Métodos

void

action_press ( String action, float strength=1.0 )

void

action_release ( String action )

void

add_joy_mapping ( String mapping, bool update_existing=false )

void

flush_buffered_events ( )

Vector3

get_accelerometer ( ) const

float

get_action_raw_strength ( String action, bool exact=false ) const

float

get_action_strength ( String action, bool exact=false ) const

float

get_axis ( String negative_action, String positive_action ) const

Array

get_connected_joypads ( )

CursorShape

get_current_cursor_shape ( ) const

Vector3

get_gravity ( ) const

Vector3

get_gyroscope ( ) const

float

get_joy_axis ( int device, int axis ) const

int

get_joy_axis_index_from_string ( String axis )

String

get_joy_axis_string ( int axis_index )

int

get_joy_button_index_from_string ( String button )

String

get_joy_button_string ( int button_index )

String

get_joy_guid ( int device ) const

String

get_joy_name ( int device )

float

get_joy_vibration_duration ( int device )

Vector2

get_joy_vibration_strength ( int device )

Vector2

get_last_mouse_speed ( ) const

Vector3

get_magnetometer ( ) const

int

get_mouse_button_mask ( ) const

MouseMode

get_mouse_mode ( ) const

Vector2

get_vector ( String negative_x, String positive_x, String negative_y, String positive_y, float deadzone=-1.0 ) const

bool

is_action_just_pressed ( String action, bool exact=false ) const

bool

is_action_just_released ( String action, bool exact=false ) const

bool

is_action_pressed ( String action, bool exact=false ) const

bool

is_joy_button_pressed ( int device, int button ) const

bool

is_joy_known ( int device )

bool

is_key_pressed ( int scancode ) const

bool

is_mouse_button_pressed ( int button ) const

bool

is_physical_key_pressed ( int scancode ) const

void

joy_connection_changed ( int device, bool connected, String name, String guid )

void

parse_input_event ( InputEvent event )

void

remove_joy_mapping ( String guid )

void

set_accelerometer ( Vector3 value )

void

set_custom_mouse_cursor ( Resource image, CursorShape shape=0, Vector2 hotspot=Vector2( 0, 0 ) )

void

set_default_cursor_shape ( CursorShape shape=0 )

void

set_gravity ( Vector3 value )

void

set_gyroscope ( Vector3 value )

void

set_magnetometer ( Vector3 value )

void

set_mouse_mode ( MouseMode mode )

void

set_use_accumulated_input ( bool enable )

void

start_joy_vibration ( int device, float weak_magnitude, float strong_magnitude, float duration=0 )

void

stop_joy_vibration ( int device )

void

vibrate_handheld ( int duration_ms=500 )

void

warp_mouse_position ( Vector2 to )

Señales

  • joy_connection_changed ( int device, bool connected )

Se emite cuando se ha conectado o desconectado un dispositivo joypad.

Enumeraciones

enum MouseMode:

  • MOUSE_MODE_VISIBLE = 0 --- Hace que el cursor del ratón sea visible si está oculto.

  • MOUSE_MODE_HIDDEN = 1 --- Hace que el cursor del ratón se oculte si es visible.

  • MOUSE_MODE_CAPTURED = 2 --- Captures the mouse. The mouse will be hidden and its position locked at the center of the screen.

Note: If you want to process the mouse's movement in this mode, you need to use InputEventMouseMotion.relative.

  • MOUSE_MODE_CONFINED = 3 --- Hace visible el cursor del ratón pero lo limita a la ventana del juego.


enum CursorShape:

  • CURSOR_ARROW = 0 --- Cursor de la flecha. Cursor puntero estándar y predeterminado.

  • CURSOR_IBEAM = 1 --- Cursor del rayo I. Normalmente se usa para mostrar dónde aparecerá el cursor de texto cuando se haga clic con el ratón.

  • CURSOR_POINTING_HAND = 2 --- Apuntando con el cursor de la mano. Normalmente se usa para indicar que el puntero está sobre un enlace u otro elemento interactivo.

  • CURSOR_CROSS = 3 --- Cursor en cruz. Normalmente aparece sobre las regiones en las que se puede realizar una operación de dibujo o para realizar selecciones.

  • CURSOR_WAIT = 4 --- Espera el cursor. Indica que la aplicación está ocupada realizando una operación. La forma del cursor indica que la aplicación sigue siendo utilizable durante la operación.

  • CURSOR_BUSY = 5 --- Cursor ocupado. Indica que la aplicación está ocupada realizando una operación. Esta forma de cursor denota que la aplicación no es utilizable durante la operación (por ejemplo, algo está bloqueando su hilo principal).

  • CURSOR_DRAG = 6 --- Cursor de arrastre. Normalmente se muestra cuando se arrastra algo.

  • CURSOR_CAN_DROP = 7 --- Puede soltar el cursor. Normalmente se muestra cuando se arrastra algo para indicar que se puede soltar en la posición actual.

  • CURSOR_FORBIDDEN = 8 --- Cursor prohibido. Indica que la acción actual está prohibida (por ejemplo, al arrastrar algo) o que el control en una posición está desactivado.

  • CURSOR_VSIZE = 9 --- Cursor del ratón de tamaño vertical. Una flecha vertical de doble punta. Le dice al usuario que puede cambiar el tamaño de la ventana o del panel verticalmente.

  • CURSOR_HSIZE = 10 --- Cursor del ratón de tamaño horizontal. Una flecha horizontal de doble cabeza. Le dice al usuario que puede cambiar el tamaño de la ventana o del panel horizontalmente.

  • CURSOR_BDIAGSIZE = 11 --- La ventana cambia el tamaño del cursor del ratón. El cursor es una flecha de doble punta que va de abajo a la izquierda a arriba a la derecha. Le dice al usuario que puede cambiar el tamaño de la ventana o del panel tanto horizontal como verticalmente.

  • CURSOR_FDIAGSIZE = 12 --- La ventana cambia el tamaño del cursor del ratón. El cursor es una flecha de doble punta que va de arriba a la izquierda a abajo a la derecha, lo opuesto a CURSOR_BDIAGSIZE. Le dice al usuario que puede cambiar el tamaño de la ventana o del panel tanto horizontal como verticalmente.

  • CURSOR_MOVE = 13 --- Mueve el cursor. Indica que algo puede ser movido.

  • CURSOR_VSPLIT = 14 --- Cursor del ratón dividido verticalmente. En Windows, es lo mismo que CURSOR_VSIZE.

  • CURSOR_HSPLIT = 15 --- Cursor del ratón dividido horizontalmente. En Windows, es lo mismo que CURSOR_HSIZE.

  • CURSOR_HELP = 16 --- Cursor de ayuda. Normalmente un signo de interrogación.

Descripciones de Métodos

  • void action_press ( String action, float strength=1.0 )

Esto simulará pulsar la acción específica.

La fuerza puede ser usada para acciones no booleanas, está entre 0 y 1 representando la intensidad de la acción dada.

Nota: Este método no causará ninguna llamada al Node._input. Está pensado para ser usado con is_action_pressed y is_action_just_pressed. Si quieres simular _input, usa en su lugar parse_input_event.


  • void action_release ( String action )

Si la acción especificada ya está presionada, esto la liberará.


  • void add_joy_mapping ( String mapping, bool update_existing=false )

Añade una nueva entrada de mapeo (en formato SDL2) a la base de datos de mapeo. Opcionalmente actualiza los dispositivos ya conectados.


  • void flush_buffered_events ( )

Sends all input events which are in the current buffer to the game loop. These events may have been buffered as a result of accumulated input (set_use_accumulated_input) or agile input flushing (ProjectSettings.input_devices/buffering/agile_event_flushing).

The engine will already do this itself at key execution points (at least once per frame). However, this can be useful in advanced cases where you want precise control over the timing of event handling.


  • Vector3 get_accelerometer ( ) const

Returns the acceleration of the device's accelerometer sensor, if the device has one. Otherwise, the method returns Vector3.ZERO.

Note this method returns an empty Vector3 when running from the editor even when your device has an accelerometer. You must export your project to a supported device to read values from the accelerometer.

Note: This method only works on iOS, Android, and UWP. On other platforms, it always returns Vector3.ZERO. On Android the unit of measurement for each axis is m/s² while on iOS and UWP it's a multiple of the Earth's gravitational acceleration g (~9.81 m/s²).


Returns a value between 0 and 1 representing the raw intensity of the given action, ignoring the action's deadzone. In most cases, you should use get_action_strength instead.

If exact is false, it ignores the input modifiers for InputEventKey and InputEventMouseButton events, and the direction for InputEventJoypadMotion events.


Returns a value between 0 and 1 representing the intensity of the given action. In a joypad, for example, the further away the axis (analog sticks or L2, R2 triggers) is from the dead zone, the closer the value will be to 1. If the action is mapped to a control that has no axis as the keyboard, the value returned will be 0 or 1.

If exact is false, it ignores the input modifiers for InputEventKey and InputEventMouseButton events, and the direction for InputEventJoypadMotion events.


Get axis input by specifying two actions, one negative and one positive.

This is a shorthand for writing Input.get_action_strength("positive_action") - Input.get_action_strength("negative_action").


  • Array get_connected_joypads ( )

Devuelve un Array que contiene los Ids de los dispositivos de todos los joypads conectados actualmente.


Devuelve la forma del cursor actualmente asignada (véase CursorShape).


Returns the gravity of the device's accelerometer sensor, if the device has one. Otherwise, the method returns Vector3.ZERO.

Note: This method only works on Android and iOS. On other platforms, it always returns Vector3.ZERO. On Android the unit of measurement for each axis is m/s² while on iOS it's a multiple of the Earth's gravitational acceleration g (~9.81 m/s²).


Returns the rotation rate in rad/s around a device's X, Y, and Z axes of the gyroscope sensor, if the device has one. Otherwise, the method returns Vector3.ZERO.

Note: This method only works on Android and iOS. On other platforms, it always returns Vector3.ZERO.


Returns the current value of the joypad axis at given index (see JoystickList).


  • int get_joy_axis_index_from_string ( String axis )

Devuelve el índice del nombre del eje suministrado.


  • String get_joy_axis_string ( int axis_index )

Receives a JoystickList axis and returns its equivalent name as a string.


  • int get_joy_button_index_from_string ( String button )

Devuelve el índice del nombre del botón proporcionado.


  • String get_joy_button_string ( int button_index )

Receives a gamepad button from JoystickList and returns its equivalent name as a string.


Devuelve una GUID de dispositivo compatible con SDL2 en las plataformas que usan remapeo de gamepad. Devuelve "Default Gamepad" de otra manera.


Devuelve el nombre del joypad en el índice del dispositivo especificado.


  • float get_joy_vibration_duration ( int device )

Devuelve la duración del efecto de la vibración actual en segundos.


  • Vector2 get_joy_vibration_strength ( int device )

Devuelve la fuerza de la vibración del joypad: x es la fuerza del motor débil, e y es la fuerza del motor fuerte.


  • Vector2 get_last_mouse_speed ( ) const

Devuelve la velocidad del ratón, la última vez que se movió el cursor, y esto hasta el siguiente fotograma donde el ratón se mueve. Esto significa que aunque el ratón no se mueva, esta función seguirá devolviendo el valor del último movimiento.


  • Vector3 get_magnetometer ( ) const

Returns the magnetic field strength in micro-Tesla for all axes of the device's magnetometer sensor, if the device has one. Otherwise, the method returns Vector3.ZERO.

Note: This method only works on Android, iOS and UWP. On other platforms, it always returns Vector3.ZERO.


  • int get_mouse_button_mask ( ) const

Devuelve los botones del ratón como una máscara de bits. Si se pulsan varios botones del ratón al mismo tiempo, los bits se suman.


Devuelve el modo de ratón. Vea las constantes para más información.


Gets an input vector by specifying four actions for the positive and negative X and Y axes.

This method is useful when getting vector input, such as from a joystick, directional pad, arrows, or WASD. The vector has its length limited to 1 and has a circular deadzone, which is useful for using vector input as movement.

By default, the deadzone is automatically calculated from the average of the action deadzones. However, you can override the deadzone to be whatever you want (on the range of 0 to 1).


  • bool is_action_just_pressed ( String action, bool exact=false ) const

Returns true when the user starts pressing the action event, meaning it's true only on the frame that the user pressed down the button.

This is useful for code that needs to run only once when an action is pressed, instead of every frame while it's pressed.

If exact is false, it ignores the input modifiers for InputEventKey and InputEventMouseButton events, and the direction for InputEventJoypadMotion events.


  • bool is_action_just_released ( String action, bool exact=false ) const

Returns true when the user stops pressing the action event, meaning it's true only on the frame that the user released the button.

If exact is false, it ignores the input modifiers for InputEventKey and InputEventMouseButton events, and the direction for InputEventJoypadMotion events.


Returns true if you are pressing the action event. Note that if an action has multiple buttons assigned and more than one of them is pressed, releasing one button will release the action, even if some other button assigned to this action is still pressed.

If exact is false, it ignores the input modifiers for InputEventKey and InputEventMouseButton events, and the direction for InputEventJoypadMotion events.


  • bool is_joy_button_pressed ( int device, int button ) const

Returns true if you are pressing the joypad button (see JoystickList).


Returns true if the system knows the specified device. This means that it sets all button and axis indices exactly as defined in JoystickList. Unknown joypads are not expected to match these constants, but you can still retrieve events from them.


  • bool is_key_pressed ( int scancode ) const

Returns true if you are pressing the key. You can pass a KeyList constant.


  • bool is_mouse_button_pressed ( int button ) const

Devuelve true si se pulsa el botón del ratón especificado con ButtonList.


  • bool is_physical_key_pressed ( int scancode ) 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 KeyList constant.


Notifica al singleton Input que una conexión ha cambiado, para actualizar el estado del índice del device.

Este índice se utiliza internamente y no debería tener que ser llamado desde los scripts de usuario. Véase joy_connection_changed para la señal emitida cuando se activa internamente.


Alimenta un InputEvent al juego. Puede ser usado para disparar artificialmente eventos de entrada desde el código. También genera llamadas de Node._input.

Ejemplo:

var evento = InputEventAction.new()
evento.action = "ui_cancel"
evento.pressed = true
Input.parse_input_event(evento)

  • void remove_joy_mapping ( String guid )

Elimina todos los mapeos de la base de datos interna que coincidan con la GUID dada.


  • void set_accelerometer ( Vector3 value )

Sets the acceleration value of the accelerometer sensor. Can be used for debugging on devices without a hardware sensor, for example in an editor on a PC.

Note: This value can be immediately overwritten by the hardware sensor value on Android and iOS.


Establece una imagen personalizada del cursor del ratón, que sólo es visible dentro de la ventana del juego. También se puede especificar el punto de acceso. Al pasar null al parámetro de la imagen se restablece el cursor del sistema. Ver CursorShape para la lista de formas.

image debe ser inferior a 256×256.

hotspot debe estar dentro del tamaño de image.

**Nota: ** AnimatedTextures no están soportados como cursores de ratón personalizados. Si se utiliza una AnimatedTexture, sólo se mostrará el primer fotograma.

Nota: Sólo se admiten las imágenes importadas con los modos de compresión SinPerdida, ConPerdida o SinCompresion. El modo de compresión Video RAM no puede utilizarse para cursores personalizados.


  • void set_default_cursor_shape ( CursorShape shape=0 )

Establece la forma del cursor por defecto para ser usado en la vista en lugar de la CURSOR_ARROW.

Nota: Si quieres cambiar la forma del cursor por defecto para los nodos de Control, usa Control.mouse_default_cursor_shape en su lugar.

Nota: Este método genera un InputEventMouseMotion para actualizar el cursor inmediatamente.


  • void set_gravity ( Vector3 value )

Sets the gravity value of the accelerometer sensor. Can be used for debugging on devices without a hardware sensor, for example in an editor on a PC.

Note: This value can be immediately overwritten by the hardware sensor value on Android and iOS.


  • void set_gyroscope ( Vector3 value )

Sets the value of the rotation rate of the gyroscope sensor. Can be used for debugging on devices without a hardware sensor, for example in an editor on a PC.

Note: This value can be immediately overwritten by the hardware sensor value on Android and iOS.


  • void set_magnetometer ( Vector3 value )

Sets the value of the magnetic field of the magnetometer sensor. Can be used for debugging on devices without a hardware sensor, for example in an editor on a PC.

Note: This value can be immediately overwritten by the hardware sensor value on Android and iOS.


Establece el modo del ratón. Vea las constantes para más información.


  • void set_use_accumulated_input ( bool enable )

Habilita o deshabilita la acumulación de eventos de entrada similares enviados por el sistema operativo. Cuando la acumulación de entrada está activada, todos los eventos de entrada generados durante una trama se fusionarán y se emitirán cuando la trama se termine de renderizar. Por lo tanto, esto limita el número de llamadas del método de entrada por segundo al FPS de renderización.

La acumulación de entrada está habilitada por defecto. Se puede desactivar para obtener una entrada ligeramente más precisa/reactiva a costa de un mayor uso de la CPU. En aplicaciones donde se requiere dibujar líneas a mano alzada, la acumulación de entrada generalmente debe deshabilitarse mientras el usuario está dibujando la línea para obtener resultados que sigan de cerca la entrada real.


  • void start_joy_vibration ( int device, float weak_magnitude, float strong_magnitude, float duration=0 )

Empieza a vibrar el joypad. Los joypads suelen tener dos motores de vibración, uno fuerte y otro débil. weak_magnitude es la fuerza del motor débil (entre 0 y 1) y strong_magnitude es la fuerza del motor fuerte (entre 0 y 1). duración es la duración del efecto en segundos (una duración de 0 intentará reproducir la vibración indefinidamente).

Nota: No todos los equipos son compatibles con las duraciones de efecto largas; se recomienda reiniciar un efecto si tiene que ser reproducido durante más de unos pocos segundos.


  • void stop_joy_vibration ( int device )

Detiene la vibración del joypad.


  • void vibrate_handheld ( int duration_ms=500 )

Vibrate Android and iOS devices.

Note: It needs VIBRATE permission for Android at export settings. iOS does not support duration.


  • void warp_mouse_position ( Vector2 to )

Establece la posición del ratón en el vector especificado.