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...
Usando Señales¶
En esta lección, veremos las señales. Son mensajes que emiten los nodos cuando les sucede algo específico, como que se presiona un botón. Otros nodos pueden conectarse a esa señal y llamar a una función cuando ocurra el evento.
Las señales son un mecanismo de delegación incorporado en Godot que permite a un objeto del juego reaccionar a un cambio en otro sin que se referencien entre sí. El uso de señales limita el acoplamiento y mantiene tu código flexible.
For example, you might have a life bar on the screen that represents the player's health. When the player takes damage or uses a healing potion, you want the bar to reflect the change. To do so, in Godot, you would use signals.
Nota
Como se mencionó en la introducción, las señales son la versión de Godot del patrón observador. Puede obtener más información al respecto aquí: https://gameprogrammingpatterns.com/observer.htm
Ahora utilizaremos una señal para hacer que nuestro icono de Godot de la lección anterior (Escuchando la entrada del jugador) se mueva y se detenga pulsando un botón.
Configuración de la escena¶
To add a button to our game, we will create a new main scene which will include
both a Button and the sprite_2d.tscn
scene we created in
the Creando tu primer script lesson.
Cree una nueva escena yendo al menú Escenas -> Nueva escena.

In the Scene dock, click the 2D Scene button. This will add a Node2D as our root.

In the FileSystem dock, click and drag the sprite_2d.tscn
file you saved
previously onto the Node2D to instantiate it.

We want to add another node as a sibling of the Sprite2D. To do so, right-click on Node2D and select Add Child Node.

Search for the Button node and add it.

El nodo es pequeño por defecto. Haga clic y arrastre el controlador inferior derecho del botón en el viewport para cambiar su tamaño.

Si no ve los controladores, asegúrese de que la herramienta de selección esté activa en la barra de herramientas.

Haz clic y arrastra el botón para moverlo más cerca del sprite.
You can also write a label on the Button by editing its Text property in the
Inspector. Enter Toggle motion
.

Tu árbol de escenas y el viewport deberían verse así.

Save your newly created scene as node_2d.tscn
, if you haven't already.
You can then run it with F6 (Cmd + R on macOS).
At the moment, the button will be visible, but nothing will happen if you
press it.
Conexión de una señal en el editor¶
Here, we want to connect the Button's "pressed" signal to our Sprite2D, and we want to call a new function that will toggle its motion on and off. We need to have a script attached to the Sprite2D node, which we do from the previous lesson.
Puede conectar señales en el panel Nodos. Seleccione el nodo Button y, en el lado derecho del editor, haga clic en la pestaña denominada "Nodos" junto al Inspector.

El panel muestra una lista de señales disponibles en el nodo seleccionado.

Haga doble clic en la señal "pressed" para abrir la ventana de conexión del nodo.

There, you can connect the signal to the Sprite2D node. The node needs a receiver method, a function that Godot will call when the Button emits the signal. The editor generates one for you. By convention, we name these callback methods "_on_node_name_signal_name". Here, it'll be "_on_button_pressed".
Nota
Al conectar señales a través del panel de Nodos del editor, puede usar dos modos. El simple solo le permite conectarse a nodos que tienen un script adjunto y crea una nueva función de devolución de llamada en ellos.

La vista avanzada le permite conectarse a cualquier nodo y a cualquier función incorporada, añadir argumentos a la llamada de retorno y establecer opciones. Puedes cambiar el modo en la parte inferior derecha de la ventana haciendo clic en el botón Avanzado.
Haga clic en el botón Conectar para completar la conexión de la señal y saltar al espacio de trabajo Script. Debería ver el nuevo método con un icono de conexión en el margen izquierdo.

Si hace clic en el icono, aparece una ventana que muestra información sobre la conexión. Esta función solo está disponible cuando se conectan nodos en el editor.

Reemplacemos la línea con la palabra clave pass
con código que cambiará el movimiento del nodo.
Our Sprite2D moves thanks to code in the _process()
function. Godot provides
a method to toggle processing on and off: Node.set_process(). Another method of the Node class,
is_processing()
, returns true
if idle processing is active. We can use
the not
keyword to invert the value.
func _on_button_pressed():
set_process(not is_processing())
private void OnButtonPressed()
{
SetProcess(!IsProcessing());
}
Esta función alternará el procesamiento y, sucesivamente, la moción del icono entre activa e inactiva tras apretar el botón.
Antes de probar el juego, debemos simplificar nuestra función _process()
para mover el nodo automaticamente y no esperar un aporte del usuario. Remplazalo con el siguiente código, el cual vimos hace dos lecciones:
func _process(delta):
rotation += angular_speed * delta
var velocity = Vector2.UP.rotated(rotation) * speed
position += velocity * delta
public override void _Process(double delta)
{
Rotation += _angularSpeed * (float)delta;
var velocity = Vector2.Up.Rotated(Rotation) * _speed;
Position += velocity * (float)delta;
}
Your complete sprite_2d.gd
code should look like the following.
extends Sprite2D
var speed = 400
var angular_speed = PI
func _process(delta):
rotation += angular_speed * delta
var velocity = Vector2.UP.rotated(rotation) * speed
position += velocity * delta
func _on_button_pressed():
set_process(not is_processing())
using Godot;
public partial class MySprite2D : Sprite2D
{
private float _speed = 400;
private float _angularSpeed = Mathf.Pi;
public override void _Process(double delta)
{
Rotation += _angularSpeed * (float)delta;
var velocity = Vector2.Up.Rotated(Rotation) * _speed;
Position += velocity * (float)delta;
}
private void OnButtonPressed()
{
SetProcess(!IsProcessing());
}
}
Ejecuta la escena y haz clic en el botón para ver el sprite comenzar y parar.
Conexión de una señal a través de código¶
Puedes conectar señales a través de código en vez de usar el editor. Esto es necesario cuando creas nodos o representas escenas usando instancias dentro de un script.
Vamos a usar un nodo diferente aquí. Godot tiene un nodo Timer que es útil para implementar tiempos de espera para habilidades, recargas de armas, y más.
Regrese al espacio de trabajo 2D. Puede hacer clic en el texto "2D" en la parte superior de la ventana o presionar Ctrl + F1 (Alt + 1 en macOS).
In the Scene dock, right-click on the Sprite2D node and add a new child node. Search for Timer and add the corresponding node. Your scene should now look like this.

With the Timer node selected, go to the Inspector and enable the Autostart property.

Click the script icon next to Sprite2D to jump back to the scripting workspace.

Debemos hacer dos operaciones para conectar los nodos con código:
Get a reference to the Timer from the Sprite2D.
Call the
connect()
method on the Timer's "timeout" signal.
Nota
To connect to a signal via code, you need to call the connect()
method of the signal you want to listen to. In this case, we want to
listen to the Timer's "timeout" signal.
Queremos conectar la señal cuando la escena es instanciada, y podemos hacerlo usando la función integrada Node._ready(), que el motor llama automáticamente cuando un nodo está completamente instanciado.
Para obtener una referencia al nodo relativo al actual, usamos el método Node.get_node(). Podemos almacenar la referencia en una variable.
func _ready():
var timer = get_node("Timer")
public override void _Ready()
{
var timer = GetNode<Timer>("Timer");
}
The function get_node()
looks at the Sprite2D's children and gets nodes by
their name. For example, if you renamed the Timer node to "BlinkingTimer" in the
editor, you would have to change the call to get_node("BlinkingTimer")
.
We can now connect the Timer to the Sprite2D in the _ready()
function.
func _ready():
var timer = get_node("Timer")
timer.timeout.connect(_on_timer_timeout)
public override void _Ready()
{
var timer = GetNode<Timer>("Timer");
timer.Timeout += OnTimerTimeout;
}
The line reads like so: we connect the Timer's "timeout" signal to the node to
which the script is attached. When the Timer emits timeout
, we want to call
the function _on_timer_timeout()
, that we need to define. Let's add it at the
bottom of our script and use it to toggle our sprite's visibility.
Nota
By convention, we name these callback methods in GDScript as "_on_node_name_signal_name" and in C# as "OnNodeNameSignalName". Here, it'll be "_on_timer_timeout" for GDScript and OnTimerTimeout() for C#.
func _on_timer_timeout():
visible = not visible
private void OnTimerTimeout()
{
Visible = !Visible;
}
La propiedad visible``es un boolean que controla la visibilidad de nuestro nodo. La línea ``visible = not visible``alterna el valor. Si ``visible
es true
, se vuelve false
, y vice-versa.
Si ejecuta la escena ahora, verá que el sprite se enciende y se apaga, a intervalos de un segundo.
Script completo¶
That's it for our little moving and blinking Godot icon demo!
Here is the complete sprite_2d.gd
file for reference.
extends Sprite2D
var speed = 400
var angular_speed = PI
func _ready():
var timer = get_node("Timer")
timer.timeout.connect(_on_timer_timeout)
func _process(delta):
rotation += angular_speed * delta
var velocity = Vector2.UP.rotated(rotation) * speed
position += velocity * delta
func _on_button_pressed():
set_process(not is_processing())
func _on_timer_timeout():
visible = not visible
using Godot;
public partial class MySprite2D : Sprite2D
{
private float _speed = 400;
private float _angularSpeed = Mathf.Pi;
public override void _Ready()
{
var timer = GetNode<Timer>("Timer");
timer.Timeout += OnTimerTimeout;
}
public override void _Process(double delta)
{
Rotation += _angularSpeed * (float)delta;
var velocity = Vector2.Up.Rotated(Rotation) * _speed;
Position += velocity * (float)delta;
}
private void OnButtonPressed()
{
SetProcess(!IsProcessing());
}
private void OnTimerTimeout()
{
Visible = !Visible;
}
}
Señales personalizadas¶
Nota
Está sección es una referencia de cómo definir y usar tus propias señales, y no se basa en el proyecto creado en lecciones anteriores.
Puedes definir señales personalizadas en un script. Digamos, por ejemplo, que quieres mostrar una pantalla de derrota cuando la vida del jugador alcanza 0. Para hacerlo, podrías definir una señal llamada "died" o "health_depleted" cuando su vida llegue a 0.
extends Node2D
signal health_depleted
var health = 10
using Godot;
public partial class MyNode2D : Node2D
{
[Signal]
public delegate void HealthDepletedEventHandler();
private int _health = 10;
}
Nota
Como las señales representan eventos que acaban de ocurrir, generalmente usamos un verbo en pasado como nombre.
Tus señales funcionan de la misma manera que las incorporadas: aparecen en la pestaña Nodos y puede conectarse a ellas como cualquier otra.

To emit a signal in your scripts, call emit()
on the signal.
func take_damage(amount):
health -= amount
if health <= 0:
health_depleted.emit()
public void TakeDamage(int amount)
{
_health -= amount;
if (_health <= 0)
{
EmitSignal(SignalName.HealthDepleted);
}
}
Una señal puede declarar opcionalmente uno o más argumentos. Especifique los nombres de los argumentos entre paréntesis:
extends Node
signal health_changed(old_value, new_value)
var health = 10
using Godot;
public partial class MyNode : Node
{
[Signal]
public delegate void HealthChangedEventHandler(int oldValue, int newValue);
private int _health = 10;
}
Nota
Estos argumentos se muestran en el panel de nodos del editor, y Godot puede usarlos para generar funciones de callback para usted. Sin embargo, usted puede seguir emitiendo cualquier número de argumentos cuando emite señales, así que depende de usted emitir los valores correctos.
To emit values along with the signal, add them as extra arguments to the
emit()
function:
func take_damage(amount):
var old_health = health
health -= amount
health_changed.emit(old_health, health)
public void TakeDamage(int amount)
{
int oldHealth = _health;
_health -= amount;
EmitSignal(SignalName.HealthChanged, oldHealth, _health);
}
Sumario¶
Cualquier nodo en Godot emite señales cuando les sucede algo específico, como cuando se presiona un botón. Otros nodos pueden conectarse a señales individuales y reaccionar a eventos seleccionados.
Las señales tienen muchos usos. Con ellos, puedes reaccionar a un nodo que entra o sale del mundo del juego, a una colisión, a un personaje que entra o sale de un área, a un elemento de la interfaz que cambia de tamaño y mucho más.
Por ejemplo, un Area2D que representa una moneda emite una señal body_entered
cada vez que el cuerpo físico del jugador entra en su forma de colisión, permitiéndote saber cuándo el jugador la recogió.
En la siguiente sección, Tu primer juego 2D, crearás un juego 2D completo y pondrás en práctica todo lo que has aprendido hasta ahora.