Godot Version
4.3
Question
I’m making a platformer whose spikes are instantiated from a tilemap. I created a signal to be emitted from the area 2d of the instantiated scene, which in turn emits a signal from the main node 2d of the spike scene. However, I am unaware how to connect the signal in the instanced scenes to a function in the scene in which the tilemap exists. How do I do this? Would instantiating another node and connecting its signal do the trick, or something involving the packedScene? And if it isn’t possible, is there a workaround?
These are the main parts of my code:
extends Node2D
signal spike_touched(body: Node2D)
func _on_spike_collision_detector_body_entered(body: Node2D) -> void:
spike_touched.emit(body)
Maybe you could flip the spike logic since it seems like an unnecessary signal anyways, it’s a duplicate of body_entered.
Instead of emitting another signal you process the collision on the spike script, something along these lines
extends Node2D
func _on_spike_collision_detector_body_entered(body: Node2D) -> void:
if body is Player:
body.take_damage(1)
ah, I could do that, but wouldn’t that need me to have a reference to the player? the two aren’t in the same scene. Do I preload the player PackedScene and use that to check if the body is the player?
The body
is the other colliding object, which may or may not be the player. Using an if
statement you can deduce what has collided and therefor what the body
is.
You could do this by the player node’s name body.name
, groups body.is_in_group()
, or class_name Player
such as my example with the keyword is
.
ah I forgot groups, could I also maybe use a singleton for the player?
I would not use a singleton for the player. I make use of class_name
fairly often, this defines a type for the specified script that is globally recognized, but not a singleton.
In you player script you can add class_name Player
directly before or after extends
extends CharacterBody2D
class_name Player
var health: int = 100
func take_damage(amount: int) -> void:
health -= amount
if health <= 0:
pass # game over
aight then, thanks a lot for the help!