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¶
Señales¶
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¶
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á.
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.
CursorShape get_current_cursor_shape ( ) const
Devuelve la forma del cursor actualmente asignada (véase CursorShape).
Vector3 get_gravity ( ) const
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²).
Vector3 get_gyroscope ( ) const
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).
Devuelve el índice del nombre del eje suministrado.
Receives a JoystickList axis and returns its equivalent name as a string.
Devuelve el índice del nombre del botón proporcionado.
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.
Devuelve la duración del efecto de la vibración actual en segundos.
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.
MouseMode get_mouse_mode ( ) const
Devuelve el modo de ratón. Vea las constantes para más información.
Vector2 get_vector ( String negative_x, String positive_x, String negative_y, String positive_y, float deadzone=-1.0 ) const
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).
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.
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.
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.
Returns true
if you are pressing the key. You can pass a KeyList constant.
Devuelve true
si se pulsa el botón del ratón especificado con ButtonList.
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.
void parse_input_event ( InputEvent event )
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.
void set_custom_mouse_cursor ( Resource image, CursorShape shape=0, Vector2 hotspot=Vector2( 0, 0 ) )
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.
void set_mouse_mode ( MouseMode mode )
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.