Node

Inherits: Object

Inherited By: AnimationPlayer, AnimationTree, AnimationTreePlayer, AudioStreamPlayer, CanvasItem, CanvasLayer, EditorFileSystem, EditorInterface, EditorPlugin, EditorResourcePreview, HTTPRequest, InstancePlaceholder, ResourcePreloader, SkeletonIK, Spatial, Timer, Tween, Viewport, WorldEnvironment

Clase base para todos los objetos escena.

Descripción

Los nodos son los componentes básicos de Godot. Se pueden asignar como hijos de otro nodo, lo que da como resultado una disposición de árbol. Un nodo dado puede contener cualquier número de nodos como hijos con el requisito de que todos los hermanos (hijos directos de un nodo) deben tener nombres únicos.

Un árbol de nodos se llama escena. Las escenas se pueden guardar en el disco y luego instanciarlas en otras escenas. Esto permite una gran flexibilidad en la arquitectura y el modelo de datos de los proyectos de Godot.

Árbol de escenas: El SceneTree contiene el árbol activo de nodos. Cuando se agrega un nodo al árbol de la escena, recibe la notificación NOTIFICATION_ENTER_TREE constante y se activa su devolución de llamada _enter_tree. Los nodos secundarios siempre se agregan después de su nodo principal, es decir, la devolución de llamada del _enter_tree de un nodo principal se activará antes que su nodo principal.

Una vez que se han agregado todos los nodos en el árbol de escenas, reciben la notificación NOTIFICATION_READY y se activan sus respectivas devoluciones de llamada de _ready. Para grupos de nodos, la devolución de llamada _ready se llama en orden inverso, comenzando con los nodos secundarios y subiendo a los nodos principales.

Esto significa que al agregar un nodo al árbol de la escena, se usará el siguiente orden para las devoluciones de llamada: _enter_tree del padre, _enter_tree de los hijos, _ready de los hijos y finalmente _ready del padre (recursivamente para todo el árbol de escenas).

Procesamiento: Los nodos pueden anular el estado de "proceso", para que reciban una devolución de llamada en cada marco solicitándoles que procesen (hagan algo). El procesamiento normal (devolución de llamada _process, conmutado con set_process) ocurre lo más rápido posible y depende de la velocidad de fotogramas, por lo que el tiempo de procesamiento delta se pasa como argumento. El procesamiento de física (devolución de llamada _physics_process, alternado con set_physics_process) ocurre un número fijo de veces por segundo (60 por defecto) y es útil para el código relacionado con el motor de física.

Los nodos también pueden procesar eventos de entrada. Cuando esté presente, se llamará a la función _input para cada entrada que reciba el programa. En muchos casos, esto puede ser excesivo (a menos que se use para proyectos simples), y la función _unhandled_input podría ser preferible; se llama cuando el evento de entrada no fue manejado por nadie más (típicamente, nodos GUI Control), asegurando que el nodo solo reciba los eventos que estaban destinados a él.

Para realizar un seguimiento de la jerarquía de escenas (especialmente cuando se instalan escenas en otras escenas), se puede establecer un "propietario" para el nodo con la propiedad owner. Esto realiza un seguimiento de quién instancia qué. Sin embargo, esto es sobre todo útil cuando se escriben editores y herramientas.

Finalmente, cuando un nodo se libera con Object.free o queue_free, también liberará a todos sus hijos.

Grupos: Los nodos se pueden agregar a tantos grupos como quieras para que sea fácil de administrar, puedes crear grupos como "enemigos" o "coleccionables", por ejemplo, dependiendo de tu juego. Consulte add_to_group, is_in_group y remove_from_group. A continuación, puede recuperar todos los nodos de estos grupos, iterarlos e incluso llamar a métodos en grupos a través de los métodos en SceneTree.

Conexión en red con nodos: Después de conectarse a un servidor (o crear uno, consulte NetworkedMultiplayerENet), es posible utilizar el sistema integrado RPC (llamada a procedimiento remoto) para comunicarse a través de la red. Al llamar a rpc con un nombre de método, se llamará localmente y en todos los pares conectados (pares = clientes y el servidor que acepta conexiones). Para identificar qué nodo recibe la llamada RPC, Godot usará su NodePath (asegúrese de que los nombres de los nodos sean los mismos en todos los pares). Además, eche un vistazo al tutorial de redes de alto nivel y las demostraciones correspondientes.

Tutoriales

Propiedades

MultiplayerAPI

custom_multiplayer

String

filename

MultiplayerAPI

multiplayer

String

name

Node

owner

PauseMode

pause_mode

0

int

process_priority

0

Métodos

void

_enter_tree ( ) virtual

void

_exit_tree ( ) virtual

String

_get_configuration_warning ( ) virtual

void

_input ( InputEvent event ) virtual

void

_physics_process ( float delta ) virtual

void

_process ( float delta ) virtual

void

_ready ( ) virtual

void

_unhandled_input ( InputEvent event ) virtual

void

_unhandled_key_input ( InputEventKey event ) virtual

void

add_child ( Node node, bool legible_unique_name=false )

void

add_child_below_node ( Node node, Node child_node, bool legible_unique_name=false )

void

add_to_group ( String group, bool persistent=false )

bool

can_process ( ) const

Node

duplicate ( int flags=15 ) const

Node

find_node ( String mask, bool recursive=true, bool owned=true ) const

Node

find_parent ( String mask ) const

Node

get_child ( int idx ) const

int

get_child_count ( ) const

Array

get_children ( ) const

Array

get_groups ( ) const

int

get_index ( ) const

int

get_network_master ( ) const

Node

get_node ( NodePath path ) const

Array

get_node_and_resource ( NodePath path )

Node

get_node_or_null ( NodePath path ) const

Node

get_parent ( ) const

NodePath

get_path ( ) const

NodePath

get_path_to ( Node node ) const

float

get_physics_process_delta_time ( ) const

int

get_position_in_parent ( ) const

float

get_process_delta_time ( ) const

bool

get_scene_instance_load_placeholder ( ) const

SceneTree

get_tree ( ) const

Viewport

get_viewport ( ) const

bool

has_node ( NodePath path ) const

bool

has_node_and_resource ( NodePath path ) const

bool

is_a_parent_of ( Node node ) const

bool

is_displayed_folded ( ) const

bool

is_greater_than ( Node node ) const

bool

is_in_group ( String group ) const

bool

is_inside_tree ( ) const

bool

is_network_master ( ) const

bool

is_physics_processing ( ) const

bool

is_physics_processing_internal ( ) const

bool

is_processing ( ) const

bool

is_processing_input ( ) const

bool

is_processing_internal ( ) const

bool

is_processing_unhandled_input ( ) const

bool

is_processing_unhandled_key_input ( ) const

void

move_child ( Node child_node, int to_position )

void

print_stray_nodes ( )

void

print_tree ( )

void

print_tree_pretty ( )

void

propagate_call ( String method, Array args=[ ], bool parent_first=false )

void

propagate_notification ( int what )

void

queue_free ( )

void

raise ( )

void

remove_and_skip ( )

void

remove_child ( Node node )

void

remove_from_group ( String group )

void

replace_by ( Node node, bool keep_data=false )

void

request_ready ( )

Variant

rpc ( String method, ... ) vararg

void

rpc_config ( String method, RPCMode mode )

Variant

rpc_id ( int peer_id, String method, ... ) vararg

Variant

rpc_unreliable ( String method, ... ) vararg

Variant

rpc_unreliable_id ( int peer_id, String method, ... ) vararg

void

rset ( String property, Variant value )

void

rset_config ( String property, RPCMode mode )

void

rset_id ( int peer_id, String property, Variant value )

void

rset_unreliable ( String property, Variant value )

void

rset_unreliable_id ( int peer_id, String property, Variant value )

void

set_display_folded ( bool fold )

void

set_network_master ( int id, bool recursive=true )

void

set_physics_process ( bool enable )

void

set_physics_process_internal ( bool enable )

void

set_process ( bool enable )

void

set_process_input ( bool enable )

void

set_process_internal ( bool enable )

void

set_process_unhandled_input ( bool enable )

void

set_process_unhandled_key_input ( bool enable )

void

set_scene_instance_load_placeholder ( bool load_placeholder )

void

update_configuration_warning ( )

Señales

  • ready ( )

Emitido cuando el nodo esté listo.


  • renamed ( )

Emitido cuando el nodo es renombrado.


  • tree_entered ( )

Emitido cuando el nodo entra en el árbol.


  • tree_exited ( )

Emitido después de que el nodo sale del árbol y ya no está activo.


  • tree_exiting ( )

Emitido cuando el nodo está todavía activo pero a punto de salir del árbol. Este es el lugar adecuado para la des-inicialización (o un "destructor", si se quiere).

Enumeraciones

enum PauseMode:

  • PAUSE_MODE_INHERIT = 0 --- Heredó el modo de pausa del padre del nodo. Para el nodo raíz, es equivalente a PAUSE_MODE_STOP. Por defecto.

  • PAUSE_MODE_STOP = 1 --- Detiene el procesamiento cuando el SceneTree está en pausa.

  • PAUSE_MODE_PROCESS = 2 --- Continúe el proceso sin importar el estado de pausa de SceneTree.


enum DuplicateFlags:

  • DUPLICATE_SIGNALS = 1 --- Duplica las señales del nodo.

  • DUPLICATE_GROUPS = 2 --- Duplica los grupos del nodo.

  • DUPLICATE_SCRIPTS = 4 --- Duplica los scripts del nodo.

  • DUPLICATE_USE_INSTANCING = 8 --- Duplicar usando instancias.

Una instancia permanece ligado al original, así que cuando el original cambia, la instancia también cambia.

Constantes

  • NOTIFICATION_ENTER_TREE = 10 --- Notificación recibida cuando el nodo entra en un SceneTree.

  • NOTIFICATION_EXIT_TREE = 11 --- Notificación recibida cuando el nodo está a punto de salir de un SceneTree.

  • NOTIFICATION_MOVED_IN_PARENT = 12 --- Notificación recibida cuando el nodo se mueve en el padre.

  • NOTIFICATION_READY = 13 --- Notificación recibida cuando el nodo esté listo. Véase _ready.

  • NOTIFICATION_PAUSED = 14 --- Notificación recibida cuando el nodo está en pausa.

  • NOTIFICATION_UNPAUSED = 15 --- Notificación recibida cuando el nodo no está en pausa.

  • NOTIFICATION_PHYSICS_PROCESS = 16 --- Notificación recibida en cada fotograma cuando se fija el indicador de proceso físico (ver set_physics_process).

  • NOTIFICATION_PROCESS = 17 --- Notificación recibida en cada fotograma cuando se fija el indicador de proceso (véase set_process).

  • NOTIFICATION_PARENTED = 18 --- Notificación recibida cuando un nodo se establece como hijo de otro nodo.

Nota: Esto no significa que un nodo haya entrado en el SceneTree.

  • NOTIFICATION_UNPARENTED = 19 --- Notificación recibida cuando un nodo no tiene padre (el padre o la madre lo ha eliminado de la lista de hijos).

  • NOTIFICATION_INSTANCED = 20 --- Notificación recibida cuando el nodo es instanciado.

  • NOTIFICATION_DRAG_BEGIN = 21 --- Notificación recibida cuando comienza un arrastre.

  • NOTIFICATION_DRAG_END = 22 --- Notificación recibida cuando termina un arrastre.

  • NOTIFICATION_PATH_CHANGED = 23 --- Notificación recibida cuando el NodePath del nodo cambió.

  • NOTIFICATION_INTERNAL_PROCESS = 25 --- Notificación recibida en cada fotograma cuando se fija el indicador de proceso interno (véase set_process_internal).

  • NOTIFICATION_INTERNAL_PHYSICS_PROCESS = 26 --- Notificación recibida en cada fotograma cuando se fija el flag de proceso de física interna (véase set_physics_process_internal).

  • NOTIFICATION_POST_ENTER_TREE = 27 --- Notification received when the node is ready, just before NOTIFICATION_READY is received. Unlike the latter, it's sent every time the node enters tree, instead of only once.

  • NOTIFICATION_WM_MOUSE_ENTER = 1002 --- Notificación recibida del sistema operativo cuando el ratón entra en la ventana del juego.

Implementado en plataformas de escritorio y web.

  • NOTIFICATION_WM_MOUSE_EXIT = 1003 --- Notificación recibida del sistema operativo cuando el ratón sale de la ventana del juego.

Implementado en plataformas de escritorio y web.

  • NOTIFICATION_WM_FOCUS_IN = 1004 --- Notificación recibida del sistema operativo cuando la ventana del juego está enfocada.

Implementado en todas las plataformas.

  • NOTIFICATION_WM_FOCUS_OUT = 1005 --- Notificación recibida del sistema operativo cuando la ventana del juego está desenfocada.

Implementado en todas las plataformas.

  • NOTIFICATION_WM_QUIT_REQUEST = 1006 --- Notification received from the OS when a quit request is sent (e.g. closing the window with a "Close" button or Alt+F4).

Implemented on desktop platforms.

  • NOTIFICATION_WM_GO_BACK_REQUEST = 1007 --- Notificación recibida del sistema operativo cuando se envía una solicitud de retroceso (por ejemplo, pulsando el botón "Back" en Android).

Específico de la plataforma Android.

  • NOTIFICATION_WM_UNFOCUS_REQUEST = 1008 --- Notification received from the OS when an unfocus request is sent (e.g. another OS window wants to take the focus).

No supported platforms currently send this notification.

  • NOTIFICATION_OS_MEMORY_WARNING = 1009 --- Notificación recibida del sistema operativo cuando la aplicación supera su memoria asignada.

Específico de la plataforma iOS.

  • NOTIFICATION_TRANSLATION_CHANGED = 1010 --- Notificación recibida cuando las traducciones pueden haber cambiado. Puede ser activada por el usuario al cambiar el locale. Puede utilizarse para responder a los cambios de idioma, por ejemplo, para cambiar las strings de la interfaz de usuario sobre la marcha. Útil cuando se trabaja con el soporte de traducción incorporado, como Object.tr.

  • NOTIFICATION_WM_ABOUT = 1011 --- Notificación recibida del sistema operativo cuando se envía una solicitud de información "Acerca de".

Específico de la plataforma MacOS.

  • NOTIFICATION_CRASH = 1012 --- Notificación recibida del controlador de fallos de Godot cuando el motor está a punto de fallar.

Implementado en las plataformas de escritorio si el manejador de fallos está habilitado.

  • NOTIFICATION_OS_IME_UPDATE = 1013 --- Notificación recibida del sistema operativo cuando se produce una actualización del motor del método de entrada (por ejemplo, cambio de la posición del cursor de la IME o de la string de composición).

Específico de la plataforma MacOS.

  • NOTIFICATION_APP_RESUMED = 1014 --- Notification received from the OS when the app is resumed.

Specific to the Android platform.

  • NOTIFICATION_APP_PAUSED = 1015 --- Notification received from the OS when the app is paused.

Specific to the Android platform.

Descripciones de Propiedades

Setter

set_custom_multiplayer(value)

Getter

get_custom_multiplayer()

La anulación del valor por defecto MultiplayerAPI. La anulación a null para usar la predeterminada SceneTree.


Setter

set_filename(value)

Getter

get_filename()

If a scene is instantiated from a file, its topmost node contains the absolute file path from which it was loaded in filename (e.g. res://levels/1.tscn). Otherwise, filename is set to an empty string.


Getter

get_multiplayer()

La instancia MultiplayerAPI asociada a este nodo. O bien el custom_multiplayer, o el predeterminado SceneTree uno (si está dentro del árbol).


Setter

set_name(value)

Getter

get_name()

The name of the node. This name is unique among the siblings (other child nodes from the same parent). When set to an existing name, the node will be automatically renamed.

Note: Auto-generated names might include the @ character, which is reserved for unique names when using add_child. When setting the name manually, any @ will be removed.


Setter

set_owner(value)

Getter

get_owner()

El dueño del nodo. Un nodo puede tener cualquier otro nodo como propietario (siempre que sea un padre, abuelo, etc. válido ascendente en el árbol). Cuando se guarda un nodo (usando PackedScene), todos los nodos que posee se guardarán con él. Esto permite la creación de SceneTree complejos, con instanciación y subinstanciación.


Default

0

Setter

set_pause_mode(value)

Getter

get_pause_mode()

Modo de pausa. Cómo se comportará el nodo si el SceneTree está en pausa.


  • int process_priority

Default

0

Setter

set_process_priority(value)

Getter

get_process_priority()

La prioridad del nodo en el orden de ejecución de las llamadas de procesamiento habilitadas (es decir, NOTIFICATION_PROCESS, NOTIFICATION_PHYSICS_PROCESS y sus contrapartes internas). Los nodos cuyo valor de prioridad de proceso sea lower tendrán sus devoluciones de procesamiento ejecutadas primero.

Descripciones de Métodos

  • void _enter_tree ( ) virtual

Llamado cuando el nodo entra en el SceneTree (por ejemplo, al instalarse, al cambiar de escena o después de llamar a add_child en un script). Si el nodo tiene hijos, su llamada a _enter_tree se llamará primero, y luego la de los hijos.

Corresponde a la notificación NOTIFICATION_ENTER_TREE en Object._notification.


  • void _exit_tree ( ) virtual

Llamado cuando el nodo está a punto de salir del SceneTree (por ejemplo, al liberarse, al cambiar de escena o después de llamar a remove_child en un script). Si el nodo tiene hijos, su llamada a _exit_tree se llamará al final, después de que todos sus hijos hayan dejado el árbol.

Corresponde a la notificación NOTIFICATION_EXIT_TREE en Object._notification y a la señal tree_exiting. Para ser notificado cuando el nodo ya ha dejado el árbol activo, conéctese al tree_exited.


  • String _get_configuration_warning ( ) virtual

La string devuelta por este método se muestra como una advertencia en el Scene Dock si el script que la tsobreescribe es un script tool.

Devolver una string vacía no produce ninguna advertencia.

Llame a update_configuration_warning cuando necesite actualizar el aviso para este nodo.


Called when there is an input event. The input event propagates up through the node tree until a node consumes it.

It is only called if input processing is enabled, which is done automatically if this method is overridden, and can be toggled with set_process_input.

To consume the input event and stop it propagating further to other nodes, SceneTree.set_input_as_handled can be called.

For gameplay input, _unhandled_input and _unhandled_key_input are usually a better fit as they allow the GUI to intercept the events first.

Note: This method is only called if the node is present in the scene tree (i.e. if it's not orphan).


  • void _physics_process ( float delta ) virtual

Called during the physics processing step of the main loop. Physics processing means that the frame rate is synced to the physics, i.e. the delta variable should be constant. delta is in seconds.

It is only called if physics processing is enabled, which is done automatically if this method is overridden, and can be toggled with set_physics_process.

Corresponds to the NOTIFICATION_PHYSICS_PROCESS notification in Object._notification.

Note: This method is only called if the node is present in the scene tree (i.e. if it's not orphan).


  • void _process ( float delta ) virtual

Llamado durante la etapa de procesamiento del bucle principal. El procesamiento se realiza en cada fotograma y lo más rápido posible, por lo que el tiempo delta desde el fotograma anterior no es constante.

Sólo se llama si el procesamiento está habilitado, lo que se hace automáticamente si este método es anulado, y puede ser conmutado con set_process.

Corresponde a la notificación NOTIFICATION_PROCESS en Object._notification.

Nota: Este método sólo se llama si el nodo está presente en el árbol de la escena (es decir, si no es huérfano).


  • void _ready ( ) virtual

Se llama cuando el nodo está "listo", es decir, cuando tanto el nodo como sus hijos han entrado en el árbol de la escena. Si el nodo tiene hijos, sus llamadas _ready se activan primero, y el nodo padre recibirá la notificación de listo después.

Corresponde a la notificación NOTIFICATION_READY en Object._notification. Véase también la palabra clave onready para las variables.

Normalmente se utiliza para la inicialización. Para una inicialización aún más temprana, se puede utilizar Object._init. Véase también _enter_tree.

Nota: _ready puede ser llamado sólo una vez para cada nodo. Después de eliminar un nodo del árbol de la escena y volver a añadirlo, _ready no se llamará por segunda vez. Esto puede ser obviado con la petición de otra llamada con request_ready, que puede ser llamada en cualquier lugar antes de añadir el nodo de nuevo.


  • void _unhandled_input ( InputEvent event ) virtual

Called when an InputEvent hasn't been consumed by _input or any GUI. The input event propagates up through the node tree until a node consumes it.

It is only called if unhandled input processing is enabled, which is done automatically if this method is overridden, and can be toggled with set_process_unhandled_input.

To consume the input event and stop it propagating further to other nodes, SceneTree.set_input_as_handled can be called.

For gameplay input, this and _unhandled_key_input are usually a better fit than _input as they allow the GUI to intercept the events first.

Note: This method is only called if the node is present in the scene tree (i.e. if it's not orphan).


Called when an InputEventKey hasn't been consumed by _input or any GUI. The input event propagates up through the node tree until a node consumes it.

It is only called if unhandled key input processing is enabled, which is done automatically if this method is overridden, and can be toggled with set_process_unhandled_key_input.

To consume the input event and stop it propagating further to other nodes, SceneTree.set_input_as_handled can be called.

For gameplay input, this and _unhandled_input are usually a better fit than _input as they allow the GUI to intercept the events first.

Note: This method is only called if the node is present in the scene tree (i.e. if it's not orphan).


  • void add_child ( Node node, bool legible_unique_name=false )

Adds a child node. Nodes can have any number of children, but every child must have a unique name. Child nodes are automatically deleted when the parent node is deleted, so an entire scene can be removed by deleting its topmost node.

If legible_unique_name is true, the child node will have a human-readable name based on the name of the node being instanced instead of its type.

Note: If the child node already has a parent, the function will fail. Use remove_child first to remove the node from its current parent. For example:

if child_node.get_parent():
    child_node.get_parent().remove_child(child_node)
add_child(child_node)

Note: If you want a child to be persisted to a PackedScene, you must set owner in addition to calling add_child. This is typically relevant for tool scripts and editor plugins. If add_child is called without setting owner, the newly added Node will not be visible in the scene tree, though it will be visible in the 2D/3D view.


  • void add_child_below_node ( Node node, Node child_node, bool legible_unique_name=false )

Adds child_node as a child. The child is placed below the given node in the list of children.

If legible_unique_name is true, the child node will have a human-readable name based on the name of the node being instanced instead of its type.


  • void add_to_group ( String group, bool persistent=false )

Adds the node to a group. Groups are helpers to name and organize a subset of nodes, for example "enemies" or "collectables". A node can be in any number of groups. Nodes can be assigned a group at any time, but will not be added until they are inside the scene tree (see is_inside_tree). See notes in the description, and the group methods in SceneTree.

The persistent option is used when packing node to PackedScene and saving to file. Non-persistent groups aren't stored.

Note: For performance reasons, the order of node groups is not guaranteed. The order of node groups should not be relied upon as it can vary across project runs.


  • bool can_process ( ) const

Devuelve true si el nodo puede procesar mientras el árbol de la escena está en pausa (ver pause_mode). Siempre devuelve true si el árbol de la escena no está pausado, y false si el nodo no está en el árbol.


  • Node duplicate ( int flags=15 ) const

Duplica el nodo, devolviendo un nuevo nodo.

Puedes afinar el comportamiento usando las flags (ver DuplicateFlags).

Nota: No funcionará correctamente si el nodo contiene un script con argumentos de constructor (es decir, necesita suministrar argumentos al método Object._init). En ese caso, el nodo se duplicará sin un script.


Finds a descendant of this node whose name matches mask as in String.match (i.e. case-sensitive, but "*" matches zero or more characters and "?" matches any single character except "."). Returns null if no matching Node is found.

Note: It does not match against the full path, just against individual node names.

If owned is true, this method only finds nodes whose owner is this node. This is especially important for scenes instantiated through a script, because those scenes don't have an owner.

Note: As this method walks through all the descendants of the node, it is the slowest way to get a reference to another node. Whenever possible, consider using get_node instead. To avoid using find_node too often, consider caching the node reference into a variable.


Finds the first parent of the current node whose name matches mask as in String.match (i.e. case-sensitive, but "*" matches zero or more characters and "?" matches any single character except ".").

Note: It does not match against the full path, just against individual node names.

Note: As this method walks upwards in the scene tree, it can be slow in large, deeply nested scene trees. Whenever possible, consider using get_node instead. To avoid using find_parent too often, consider caching the node reference into a variable.


Devuelve un nodo hijo por su índice (ver get_child_count). Este método se usa a menudo para iterar todos los hijos de un nodo.

Para acceder a un nodo hijo a través de su nombre, usa get_node.


  • int get_child_count ( ) const

Devuelve el número de nodos infantiles.


  • Array get_children ( ) const

Devuelve un array de referencias a los hijos del nodo.


  • Array get_groups ( ) const

Returns an array listing the groups that the node is a member of.

Note: For performance reasons, the order of node groups is not guaranteed. The order of node groups should not be relied upon as it can vary across project runs.

Note: The engine uses some group names internally (all starting with an underscore). To avoid conflicts with internal groups, do not add custom groups whose name starts with an underscore. To exclude internal groups while looping over get_groups, use the following snippet:

# Stores the node's non-internal groups only (as an array of Strings).
var non_internal_groups = []
for group in get_groups():
    if not group.begins_with("_"):
        non_internal_groups.push_back(group)

  • int get_index ( ) const

Returns the node's index, i.e. its position among the siblings of its parent.


  • int get_network_master ( ) const

Devuelve el ID del par del maestro de la red para este nodo. Ver set_network_master.


Fetches a node. The NodePath can be either a relative path (from the current node) or an absolute path (in the scene tree) to a node. If the path does not exist, null is returned and an error is logged. Attempts to access methods on the return value will result in an "Attempt to call <method> on a null instance." error.

Note: Fetching absolute paths only works when the node is inside the scene tree (see is_inside_tree).

Example: Assume your current node is Character and the following tree:

/root
/root/Character
/root/Character/Sword
/root/Character/Backpack/Dagger
/root/MyGame
/root/Swamp/Alligator
/root/Swamp/Mosquito
/root/Swamp/Goblin

Possible paths are:

get_node("Sword")
get_node("Backpack/Dagger")
get_node("../Swamp/Alligator")
get_node("/root/MyGame")

Busca un nodo y uno de sus recursos como se especifica en el subnombre de NodePath (por ejemplo, Area2D/CollisionShape2D:shape). Si se especifican varios recursos anidados en el NodePath, el último será recuperado.

El valor de retorno es un array de tamaño 3: el primer índice apunta al Node (o al null si no se encuentra), el segundo índice apunta al Resource (o al null si no se encuentra), y el tercero es el NodePath restante, si lo hay.

Por ejemplo, suponiendo que Area2D/CollisionShape2D es un nodo válido y que a su propiedad shape se le ha asignado un recurso RectangleShape2D, se podría tener este tipo de salida:

print(get_node_and_resource("Area2D/CollisionShape2D")) # [[CollisionShape2D:1161], Null, ]
print(get_node_and_resource("Area2D/CollisionShape2D:shape")) # [[CollisionShape2D:1161], [RectangleShape2D:1156], ]
print(get_node_and_resource("Area2D/CollisionShape2D:shape:extents")) # [[CollisionShape2D:1161], [RectangleShape2D:1156], :extents]

Similar a get_node, pero no registra un error si path no apunta a un Node válido.


  • Node get_parent ( ) const

Returns the parent node of the current node, or null if the node lacks a parent.


Devuelve la ruta absoluta del nodo actual. Esto sólo funciona si el nodo actual está dentro del árbol de la escena (ver is_inside_tree).


Devuelve la ruta relativa NodePath de este nodo al node especificado. Ambos nodos deben estar en la misma escena o la función fallará.


  • float get_physics_process_delta_time ( ) const

Returns the time elapsed (in seconds) since the last physics-bound frame (see _physics_process). This is always a constant value in physics processing unless the frames per second is changed via Engine.iterations_per_second.


  • int get_position_in_parent ( ) const

Devuelve el orden del nodo en la rama del árbol de la escena. Por ejemplo, si se llama al primer nodo hijo la posición es 0.


  • float get_process_delta_time ( ) const

Devuelve el tiempo transcurrido (en segundos) desde la última llamada del proceso. Este valor puede variar de un fotograma a otro.


  • bool get_scene_instance_load_placeholder ( ) const

Devuelve true si se trata de un marcador de posición de carga de instancia. Ver InstancePlaceholder.


Devuelve el SceneTree que contiene este nodo.


Devuelve el Viewport del nodo.


Devuelve true si el nodo al que apunta NodePath existe.


Devuelve true si el NodePath apunta a un nodo válido y su subnombre apunta a un recurso válido, por ejemplo, Area2D/CollisionShape2D:shape. Las propiedades que no son de tipo Resource (por ejemplo, nodos o tipos matemáticos primitivos) no se consideran recursos.


  • bool is_a_parent_of ( Node node ) const

Devuelve true si el nodo dado es un hijo directo o indirecto del nodo actual.


  • bool is_displayed_folded ( ) const

Devuelve true si el nodo está plegado (colapsado) en el muelle de la escena.


  • bool is_greater_than ( Node node ) const

Devuelve true si el nodo dado se produce más tarde en la jerarquía de la escena que el nodo actual.


Devuelve true si este nodo está en el grupo especificado. Vea las notas en la descripción, y los métodos de grupo en SceneTree.


  • bool is_inside_tree ( ) const

Devuelve true si este nodo está actualmente dentro de un SceneTree.


  • bool is_network_master ( ) const

Devuelve true si el sistema local es el maestro de este nodo.


  • bool is_physics_processing ( ) const

Devuelve true si el procesamiento de la física está activado (véase set_physics_process).


  • bool is_physics_processing_internal ( ) const

Devuelve true si el procesamiento de la física interna está activado (véase set_physics_process_internal).


  • bool is_processing ( ) const

Devuelve true si el procesamiento está activado (véase set_process).


  • bool is_processing_input ( ) const

Devuelve true si el nodo está procesando la entrada (ver set_process_input).


  • bool is_processing_internal ( ) const

Devuelve true si el procesamiento interno está activado (véase set_process_internal).


  • bool is_processing_unhandled_input ( ) const

Devuelve true si el nodo está procesando una entrada no manejada (ver set_process_unhandled_input).


  • bool is_processing_unhandled_key_input ( ) const

Devuelve true si el nodo está procesando una entrada de clave no manejada (ver set_process_unhandled_key_input).


  • void move_child ( Node child_node, int to_position )

Mueve un nodo hijo a una posición diferente (orden) entre los otros hijos. Dado que las llamadas, señales, etc. se realizan por orden de árbol, cambiar el orden de los nodos hijos puede ser útil.


  • void print_stray_nodes ( )

Imprime todos los nodos perdidos (nodos fuera del SceneTree). Se utiliza para la depuración. Funciona sólo en construcciones de depuración.


  • void print_tree ( )

Imprime el árbol a stdout. Se utiliza principalmente para fines de depuración. Esta versión muestra la ruta relativa al nodo actual, y es buena para copiar/pegar en la función get_node.

Ejemplo de salida:

ElJuego
ElJuego/Menu
ElJuego/Menu/Label
ElJuego/Menu/Camera2D
ElJuego/PantallaInicial
ElJuego/PantallaInicial/Camera2D

  • void print_tree_pretty ( )

Similar to print_tree, this prints the tree to stdout. This version displays a more graphical representation similar to what is displayed in the scene inspector. It is useful for inspecting larger trees.

Example output:

┖╴TheGame
   ┠╴Menu
     ┠╴Label
     ┖╴Camera2D
   ┖╴SplashScreen
      ┖╴Camera2D

  • void propagate_call ( String method, Array args=[ ], bool parent_first=false )

Llama al método dado (si está presente) con los argumentos dados en args en este nodo y recursivamente en todos sus hijos. Si el argumento parent_first es true, el método será llamado primero al nodo actual, y luego a todos sus hijos. Si parent_first es false, los hijos serán llamados primero.


  • void propagate_notification ( int what )

Notifica al nodo actual y a todos sus hijos de forma recursiva llamando al Object.notification en todos ellos.


  • void queue_free ( )

Queues a node for deletion at the end of the current frame. When deleted, all of its child nodes will be deleted as well. This method ensures it's safe to delete the node, contrary to Object.free. Use Object.is_queued_for_deletion to check whether a node will be deleted at the end of the frame.

Important: If you have a variable pointing to a node, it will not be assigned to null once the node is freed. Instead, it will point to a previously freed instance and you should validate it with @GDScript.is_instance_valid before attempting to call its methods or access its properties.


  • void raise ( )

Moves this node to the bottom of parent node's children hierarchy. This is often useful in GUIs (Control nodes), because their order of drawing depends on their order in the tree. The top Node is drawn first, then any siblings below the top Node in the hierarchy are successively drawn on top of it. After using raise, a Control will be drawn on top of its siblings.


  • void remove_and_skip ( )

Quita un nodo y pone a todos sus hijos como hijos del nodo padre (si existe). Todas las suscripciones de eventos que pasen por el nodo eliminado serán canceladas.


  • void remove_child ( Node node )

Removes a child node. The node is NOT deleted and must be deleted manually.

Note: This function may set the owner of the removed Node (or its descendants) to be null, if that owner is no longer a parent or ancestor.


  • void remove_from_group ( String group )

Elimina un nodo de un grupo. Vea las notas en la descripción, y los métodos de grupo en SceneTree.


  • void replace_by ( Node node, bool keep_data=false )

Replaces a node in a scene by the given one. Subscriptions that pass through this node will be lost.

Note: The given node will become the new parent of any child nodes that the replaced node had.

Note: The replaced node is not automatically freed, so you either need to keep it in a variable for later use or free it using Object.free.


  • void request_ready ( )

Solicita que se llame de nuevo a _ready. Tenga en cuenta que el método no se llamará inmediatamente, sino que está programado para cuando el nodo se añada de nuevo al árbol de la escena (véase _ready). _ready se llama sólo para el nodo que lo ha solicitado, lo que significa que necesita solicitar ready para cada niño si quiere que también llamen a _ready (en cuyo caso, se llamará a _ready en el mismo orden que normalmente).


Envía una solicitud de llamada de procedimiento a distancia para el method dado a los pares en la red (y localmente), opcionalmente enviando todos los argumentos adicionales como argumentos al método llamado por la RPC. La solicitud de llamada sólo será recibida por nodos con el mismo NodePath, incluyendo exactamente el mismo nombre de nodo. El comportamiento depende de la configuración de la RPC para el método dado, véase rpc_config. Los métodos no están expuestos a las RPC por defecto. Véase también rset y rset_config para las propiedades. Devuelve una Variant vacía.

Nota: Sólo se pueden utilizar RPCs de forma segura en clientes después de haber recibido la señal connected_to_server de la SceneTree. También es necesario hacer un seguimiento del estado de la conexión, ya sea por las señales de SceneTree como server_disconnected o comprobando SceneTree.network_peer.get_connection_status() == CONNECTION_CONNECTED.


Cambia el modo RPC para el method dado al mode dado. Ver RPCMode. Una alternativa es anotar los métodos y propiedades con las palabras clave correspondientes (remote, master, puppet, remotesync, mastersync, puppetsync). Por defecto, los métodos no están expuestos a las redes (y a los RPC). Ver también rset y rset_config para las propiedades.


Envía un rpc a un par específico identificado por peer_id (véase NetworkedMultiplayerPeer.set_target_peer). Devuelve una Variant vacía.


Envía un rpc usando un protocolo poco fiable. Devuelve una Variant vacía.


Envía un rpc a un par específico identificado por peer_id utilizando un protocolo poco fiable (véase NetworkedMultiplayerPeer.set_target_peer). Devuelve una Variant vacía.


Cambia remotamente el valor de una propiedad en otros pares (y localmente). El comportamiento depende de la configuración RPC de la propiedad dada, ver rset_config. Véase también rpc para los métodos RPC, la mayoría de la información se aplica también a este método.


Cambia el modo RPC para la property dada al mode dado. Ver RPCMode. Una alternativa es anotar los métodos y propiedades con las palabras clave correspondientes (remote, master, puppet, remotesync, mastersync, puppetsync). Por defecto, las propiedades no están expuestas a las redes (y a los RPCs). Ver también rpc y rpc_config para los métodos.


Cambia remotamente el valor de la propiedad en un par específico identificado por peer_id (véase el NetworkedMultiplayerPeer.set_target_peer).


Cambia remotamente el valor de la propiedad en otros pares (y localmente) usando un protocolo poco fiable.


Cambia remotamente el valor de la propiedad en un par específico identificado por peer_id utilizando un protocolo poco fiable (véase el NetworkedMultiplayerPeer.set_target_peer).


  • void set_display_folded ( bool fold )

Establece el estado de plegado del nodo en el muelle de la escena.


  • void set_network_master ( int id, bool recursive=true )

Establece el maestro de la red del nodo al par con el ID del par dado. El maestro de la red es el par que tiene autoridad sobre el nodo de la red. Útil en conjunción con las palabras clave master y puppet. Heredado del nodo padre por defecto, que en última instancia es el ID del par 1 (el servidor). Si recursive, el par dado se establece recursivamente como el maestro para todos los hijos de este nodo.


  • void set_physics_process ( bool enable )

Activa o desactiva el procesamiento físico (es decir, la velocidad de fotogramas fijos). Cuando un nodo está siendo procesado, recibirá una NOTIFICATION_PHYSICS_PROCESS a un intervalo fijo (normalmente 60 FPS, ver Engine.iterations_per_second para cambiar) (y se llamará a la devolución de llamada de _physics_process si existe). Se habilita automáticamente si se anula _physics_process. Cualquier llamada a esto antes de _ready será ignorada.


  • void set_physics_process_internal ( bool enable )

Enables or disables internal physics for this node. Internal physics processing happens in isolation from the normal _physics_process calls and is used by some nodes internally to guarantee proper functioning even if the node is paused or physics processing is disabled for scripting (set_physics_process). Only useful for advanced uses to manipulate built-in nodes' behavior.

Warning: Built-in Nodes rely on the internal processing for their own logic, so changing this value from your code may lead to unexpected behavior. Script access to this internal logic is provided for specific advanced uses, but is unsafe and not supported.


  • void set_process ( bool enable )

Habilita o deshabilita el procesamiento. Cuando un nodo está siendo procesado, recibirá una NOTIFICATION_PROCESS en cada fotograma dibujado (y se llamará a la devolución de llamada _process si existe). Se habilita automáticamente si se anula _process. Cualquier llamada a esto antes de _ready será ignorada.


  • void set_process_input ( bool enable )

Habilita o deshabilita el procesamiento de la entrada. ¡Esto no es necesario para los controles GUI! Se activa automáticamente si se anula _input. Cualquier llamada a esto antes de _ready será ignorada.


  • void set_process_internal ( bool enable )

Enables or disabled internal processing for this node. Internal processing happens in isolation from the normal _process calls and is used by some nodes internally to guarantee proper functioning even if the node is paused or processing is disabled for scripting (set_process). Only useful for advanced uses to manipulate built-in nodes' behavior.

Warning: Built-in Nodes rely on the internal processing for their own logic, so changing this value from your code may lead to unexpected behavior. Script access to this internal logic is provided for specific advanced uses, but is unsafe and not supported.


  • void set_process_unhandled_input ( bool enable )

Permite el procesamiento de entradas sin manejar. ¡Esto no es necesario para los controles GUI! Permite que el nodo reciba todas las entradas que no hayan sido manejadas previamente (normalmente por un Control). Se habilita automáticamente si se anula _unhandled_input. Cualquier llamada a esto antes de _ready será ignorada.


  • void set_process_unhandled_key_input ( bool enable )

Permite el procesamiento de entradas de claves sin manejar. Se activa automáticamente si se anula _unhandled_key_input. Cualquier llamada a esto antes de _ready será ignorada.


  • void set_scene_instance_load_placeholder ( bool load_placeholder )

Establece si se trata de un marcador de posición de carga de instancia. Ver InstancePlaceholder.


  • void update_configuration_warning ( )

Actualiza la advertencia que se muestra para este nodo en el Scene Dock.

Utiliza _get_configuration_warning para configurar el mensaje de advertencia a mostrar.