About "Your First 2D Game" Tutorial, Regarding Emitting Signals

Godot Version
Godot 4.2.1.stable.mono

I am currently following the “Your First 2D Game” tutorial and am confused regarding how signals work. It is in the “preparing for collisions” part of the lesson.

So we connect body_entered(body: Node2D) node to detect collision, this is quite straight-forward. But in the script we add a new signal named “hit” and I don’t understand the need for this.

func _on_body_entered(body):
	$CollisionShape2D.set_deferred("disabled", true)

This script already hides the player character when collision is detected and also disables player’s collision so the hit detection doesn’t happen multiple times. Why do we need to emit the hit signal here? The hit signal has no function or code in it. What purpose does it serve? We already performed all the actions that we need when we collide, why do we need to emit an empty “hit” signal?

I am very new to programming in general and am really not a natural at this. Thinking in code is something new to me so my perspective and understanding is very limited. If you could kindly explain I would really appreciate it. Thanks a lot in advance and have a great day!

Emitting a signal is basically a way to send a message that something happened. When you connect a signal to a function, it means that when the signal is emitted, that function is called (you can connect it to multiple functions). Let’s say the player dies. Usually that means that the game is over. Other scripts need to know about that so that they can do whatever you want them to do when the game is over (like displaying “Game Over” text). Signals are extremely useful and you will likely end up using them a lot in your projects.

You are right that if a signal is not connected to any function in your project, nothing happens. It seems that the hit signal is needed later in the tutorial when you need a way to end the game when the player is hit.

You can learn more about signals here:

1 Like

Okay I feel silly now. I had a hunch I was probably going to need it further down in the tutorial and even tried to skim through the rest of the tutorial real quick, but my brain was already tired enough so I missed it completely.

So as far as I can understand, when _on_body_entered node is activated we emit the hit signal and when hit signal is emitted, game_over function is triggered. I hope I am getting it right.

Thank you so much for your answer! Your answer is greatly appreciated and have an awesome day!

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.