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...
SceneTree¶
Maneja el bucle del juego a través de una jerarquía de nodos.
Descripción¶
As one of the most important classes, the SceneTree
manages the hierarchy of nodes in a scene as well as scenes themselves. Nodes can be added, retrieved and removed. The whole scene tree (and thus the current scene) can be paused. Scenes can be loaded, switched and reloaded.
You can also use the SceneTree
to organize your nodes into groups: every node can be assigned as many groups as you want to create, e.g. an "enemy" group. You can then iterate these groups or even call methods and set properties on all the group's members at once.
SceneTree
is the default MainLoop implementation used by scenes, and is thus in charge of the game loop.
Tutoriales¶
Propiedades¶
|
||
|
||
|
||
|
||
|
||
|
Métodos¶
call_group ( String group, String method, ... ) vararg |
|
call_group_flags ( int flags, String group, String method, ... ) vararg |
|
change_scene ( String path ) |
|
change_scene_to ( PackedScene packed_scene ) |
|
create_timer ( float time_sec, bool pause_mode_process=true ) |
|
get_frame ( ) const |
|
get_network_connected_peers ( ) const |
|
get_network_unique_id ( ) const |
|
get_node_count ( ) const |
|
get_nodes_in_group ( String group ) |
|
get_rpc_sender_id ( ) const |
|
has_network_peer ( ) const |
|
is_input_handled ( ) |
|
is_network_server ( ) const |
|
void |
notify_group ( String group, int notification ) |
void |
notify_group_flags ( int call_flags, String group, int notification ) |
void |
queue_delete ( Object obj ) |
void |
|
void |
set_auto_accept_quit ( bool enabled ) |
void |
|
void |
set_group_flags ( int call_flags, String group, String property, Variant value ) |
void |
|
void |
set_quit_on_go_back ( bool enabled ) |
void |
set_screen_stretch ( StretchMode mode, StretchAspect aspect, Vector2 minsize, float scale=1 ) |
Señales¶
connected_to_server ( )
Emitido siempre que el SceneTree
de este network_peer se conectó con éxito a un servidor. Sólo se emite en los clientes.
connection_failed ( )
Emitido siempre que el network_peer de este SceneTree
no logre establecer una conexión con un servidor. Sólo se emite en los clientes.
files_dropped ( PoolStringArray files, int screen )
Se emite cuando los archivos se arrastran desde el administrador de archivos del sistema operativo y se sueltan en la ventana del juego. Los argumentos son una lista de las rutas de los archivos y el identificador de la pantalla donde se originó el arrastre.
Emitted whenever global menu item is clicked.
idle_frame ( )
Emitido inmediatamente antes de que se llame a Node._process en cada nodo del SceneTree
.
network_peer_connected ( int id )
Emitido cada vez que el SceneTree
de este network_peer se conecta con un nuevo par. ID es el ID del nuevo par. Los clientes son notificados cuando otros clientes se conectan al mismo servidor. Al conectarse a un servidor, un cliente también recibe esta señal para el servidor (con ID 1).
network_peer_disconnected ( int id )
Emitido cada vez que el SceneTree
de este network_peer se desconecta de un par. Los clientes son notificados cuando otros clientes se desconectan del mismo servidor.
node_added ( Node node )
Se emite cada vez que se añade un nodo al SceneTree
.
node_configuration_warning_changed ( Node node )
Emitido cuando la configuración de un nodo cambió. Sólo se emite en el modo tool
.
node_removed ( Node node )
Se emite cada vez que se quita un nodo del SceneTree
.
node_renamed ( Node node )
Emitido cada vez que un nodo es renombrado.
physics_frame ( )
Emitido inmediatamente antes de que Node._physics_process sea llamado en cada nodo del SceneTree
.
screen_resized ( )
Emitted when the screen resolution (fullscreen) or window size (windowed) changes.
server_disconnected ( )
Emitido cada vez que el SceneTree
de este network_peer se desconecta del servidor. Sólo se emite en los clientes.
tree_changed ( )
Emitido cada vez que la jerarquía SceneTree
cambiaba (los niños eran movidos o renombrados, etc.).
Enumeraciones¶
enum GroupCallFlags:
GROUP_CALL_DEFAULT = 0 --- Llama a un grupo sin flags (por defecto).
GROUP_CALL_REVERSE = 1 --- Llama a un grupo en orden inverso al de la escena.
GROUP_CALL_REALTIME = 2 --- Llama a un grupo inmediatamente (las llamadas se hacen normalmente en reposo).
GROUP_CALL_UNIQUE = 4 --- Llama a un grupo sólo una vez aunque la llamada se ejecute muchas veces.
enum StretchMode:
STRETCH_MODE_DISABLED = 0 --- No stretching.
STRETCH_MODE_2D = 1 --- Render stretching in higher resolution (interpolated).
STRETCH_MODE_VIEWPORT = 2 --- Keep the specified display resolution. No interpolation. Content may appear pixelated.
enum StretchAspect:
STRETCH_ASPECT_IGNORE = 0 --- Fill the window with the content stretched to cover excessive space. Content may appear stretched.
STRETCH_ASPECT_KEEP = 1 --- Retain the same aspect ratio by padding with black bars on either axis. This prevents distortion.
STRETCH_ASPECT_KEEP_WIDTH = 2 --- Expand vertically. Left/right black bars may appear if the window is too wide.
STRETCH_ASPECT_KEEP_HEIGHT = 3 --- Expand horizontally. Top/bottom black bars may appear if the window is too tall.
STRETCH_ASPECT_EXPAND = 4 --- Expand in both directions, retaining the same aspect ratio. This prevents distortion while avoiding black bars.
Descripciones de Propiedades¶
Node current_scene
Setter |
set_current_scene(value) |
Getter |
get_current_scene() |
La escena actual.
bool debug_collisions_hint
Default |
|
Setter |
set_debug_collisions_hint(value) |
Getter |
is_debugging_collisions_hint() |
Si true
, las formas de colisión serán visibles cuando se ejecute el juego desde el editor con fines de depuración.
Default |
|
Setter |
set_debug_navigation_hint(value) |
Getter |
is_debugging_navigation_hint() |
Si true
, los polígonos de navegación serán visibles cuando se ejecute el juego desde el editor para su depuración.
Node edited_scene_root
Setter |
set_edited_scene_root(value) |
Getter |
get_edited_scene_root() |
La raíz de la escena editada.
MultiplayerAPI multiplayer
Setter |
set_multiplayer(value) |
Getter |
get_multiplayer() |
La instancia por defecto MultiplayerAPI para este SceneTree
.
bool multiplayer_poll
Default |
|
Setter |
set_multiplayer_poll_enabled(value) |
Getter |
is_multiplayer_poll_enabled() |
Si true
(valor por defecto), habilita el sondeo automático de la MultiplayerAPI para este Árbol de Escenas durante idle_frame.
Si false
, necesita llamar manualmente al MultiplayerAPI.poll para procesar los paquetes de red y entregar los RPCs/RSETs. Esto permite ejecutar RPCs/RSETs en un bucle diferente (por ejemplo, física, hilo, paso de tiempo específico) y para la protección manual Mutex cuando se accede a la MultiplayerAPI desde los hilos.
NetworkedMultiplayerPeer network_peer
Setter |
set_network_peer(value) |
Getter |
get_network_peer() |
El objeto paritario para manejar el sistema RPC (que permite efectivamente la conexión en red cuando se establece). Dependiendo del par en sí, el SceneTree
se convertirá en un servidor de red (compruébelo con is_network_server) y establecerá el modo de red del nodo raíz como maestro, o se convertirá en un par normal con el nodo raíz establecido como marioneta. Todos los nodos hijos están configurados para heredar el modo de red por defecto. El manejo de los eventos relacionados con la red (conexión, desconexión, nuevos clientes) se hace conectando a las señales de SceneTree
.
bool paused
Default |
|
Setter |
set_pause(value) |
Getter |
is_paused() |
If true
, the SceneTree
is paused. Doing so will have the following behavior:
2D and 3D physics will be stopped. This includes signals and collision detection.
Node._process, Node._physics_process and Node._input will not be called anymore in nodes.
bool refuse_new_network_connections
Default |
|
Setter |
set_refuse_new_network_connections(value) |
Getter |
is_refusing_new_network_connections() |
Si true
, el SceneTree
de network_peer rechaza las nuevas conexiones entrantes.
Viewport root
Getter |
get_root() |
The SceneTree
's root Viewport.
bool use_font_oversampling
Default |
|
Setter |
set_use_font_oversampling(value) |
Getter |
is_using_font_oversampling() |
If true
, font oversampling is enabled. This means that DynamicFonts will be rendered at higher or lower size than configured based on the viewport's scaling ratio. For example, in a viewport scaled with a factor 1.5, a font configured with size 14 would be rendered with size 21 (14 * 1.5
).
Note: Font oversampling is only used if the viewport stretch mode is STRETCH_MODE_VIEWPORT, and if the stretch aspect mode is different from STRETCH_ASPECT_IGNORE.
Note: This property is set automatically for the active SceneTree
when the project starts based on the configuration of rendering/quality/dynamic_fonts/use_oversampling
in ProjectSettings. The property can however be overridden at runtime as needed.
Descripciones de Métodos¶
Calls method
on each member of the given group. You can pass arguments to method
by specifying them at the end of the method call. This method is equivalent of calling call_group_flags with GROUP_CALL_DEFAULT flag.
Note: method
may only have 5 arguments at most (7 arguments passed to this method in total).
Note: Due to design limitations, call_group will fail silently if one of the arguments is null
.
Note: call_group will always call methods with an one-frame delay, in a way similar to Object.call_deferred. To call methods immediately, use call_group_flags with the GROUP_CALL_REALTIME flag.
Calls method
on each member of the given group, respecting the given GroupCallFlags. You can pass arguments to method
by specifying them at the end of the method call.
Note: method
may only have 5 arguments at most (8 arguments passed to this method in total).
Note: Due to design limitations, call_group_flags will fail silently if one of the arguments is null
.
# Call the method immediately and in reverse order.
get_tree().call_group_flags(SceneTree.GROUP_CALL_REALTIME | SceneTree.GROUP_CALL_REVERSE, "bases", "destroy")
Changes the running scene to the one at the given path
, after loading it into a PackedScene and creating a new instance.
Returns @GlobalScope.OK on success, @GlobalScope.ERR_CANT_OPEN if the path
cannot be loaded into a PackedScene, or @GlobalScope.ERR_CANT_CREATE if that scene cannot be instantiated.
Note: The scene change is deferred, which means that the new scene node is added on the next idle frame. You won't be able to access it immediately after the change_scene call.
Error change_scene_to ( PackedScene packed_scene )
Changes the running scene to a new instance of the given PackedScene.
Returns @GlobalScope.OK on success or @GlobalScope.ERR_CANT_CREATE if the scene cannot be instantiated.
Note: The scene change is deferred, which means that the new scene node is added on the next idle frame. You won't be able to access it immediately after the change_scene_to call.
SceneTreeTimer create_timer ( float time_sec, bool pause_mode_process=true )
Returns a SceneTreeTimer which will SceneTreeTimer.timeout after the given time in seconds elapsed in this SceneTree
. If pause_mode_process
is set to false
, pausing the SceneTree
will also pause the timer.
Commonly used to create a one-shot delay timer as in the following example:
func some_function():
print("start")
yield(get_tree().create_timer(1.0), "timeout")
print("end")
The timer will be automatically freed after its time elapses.
int get_frame ( ) const
Devuelve el número de fotogramas actual, es decir, el número total de fotogramas desde que se inició la aplicación.
PoolIntArray get_network_connected_peers ( ) const
Devuelve las identificaciones de todos los pares conectados de este SceneTree
de network_peer.
int get_network_unique_id ( ) const
Devuelve la identificación única de este SceneTree
de network_peer.
int get_node_count ( ) const
Devuelve el número de nodos en este SceneTree
.
Devuelve una lista de todos los nodos asignados al grupo dado.
int get_rpc_sender_id ( ) const
Devuelve la identificación del remitente de la última llamada RPC recibida.
Devuelve true
si el grupo dado existe.
bool has_network_peer ( ) const
Devuelve true
si hay un conjunto de network_peer.
bool is_input_handled ( )
Returns true
if the most recent InputEvent was marked as handled with set_input_as_handled.
bool is_network_server ( ) const
Devuelve true
si el network_peer de este SceneTree
está en modo servidor (escuchando las conexiones).
Envía la notificación dada a todos los miembros del group
.
Envía la notificación dada a todos los miembros del grupo
, respetando las GroupCallFlags dadas.
void queue_delete ( Object obj )
Pone en cola el objeto dado para su eliminación, retrasando la llamada al Object.free hasta después del fotograma actual.
void quit ( int exit_code=-1 )
Quits the application at the end of the current iteration. A process exit_code
can optionally be passed as an argument. If this argument is 0
or greater, it will override the OS.exit_code defined before quitting the application.
Note: On iOS this method doesn't work. Instead, as recommended by the iOS Human Interface Guidelines, the user is expected to close apps via the Home button.
Error reload_current_scene ( )
Recarga la escena actualmente activa.
Devuelve @GlobalScope.OK en el éxito, @GlobalScope.ERR_UNCONFIGURED si aún no se ha definido current_scene, @GlobalScope.ERR_CANT_OPEN si current_scene no puede ser cargada en una PackedScene, o @GlobalScope.ERR_CANT_CREATE si la escena no puede ser instanciada.
void set_auto_accept_quit ( bool enabled )
Si true
, la aplicación acepta automáticamente salir. Habilitado por defecto.
Para las plataformas móviles, véase set_quit_on_go_back.
Establece la property
dada a value
en todos los miembros del grupo dado.
Establece la property
dada a value
en todos los miembros del grupo dado, respetando las GroupCallFlags dadas.
void set_input_as_handled ( )
Marks the most recent InputEvent as handled.
void set_quit_on_go_back ( bool enabled )
If true
, the application quits automatically on going back (e.g. on Android). Enabled by default.
To handle 'Go Back' button when this option is disabled, use MainLoop.NOTIFICATION_WM_GO_BACK_REQUEST.
void set_screen_stretch ( StretchMode mode, StretchAspect aspect, Vector2 minsize, float scale=1 )
Configures screen stretching to the given StretchMode, StretchAspect, minimum size and scale
.