Resuable collision detection when scenes share the same script

Godot Version

4.4.1

Question

I have a script called GenericProp that I’m using across lots of scenes in my game. I’m trying to set up collision detection between these props so I can trigger a behaviour.

These scenes will be instantiated at runtime so I was thinking something like:

extends RigidBody2D

func _ready():
    self.connect("body_entered", _on_body_entered)

func _on_body_entered(body: Node2D):
	print("collided!")

Because all the scenes of the same type will have this script on it, I thought I could connect the signal to itself. Typing this out now I see how that doesn’t really make sense.

How should I detect collisions between instantiated scenes of the same type in Godot? I suppose I could put the scenes in a group then connect to everything in the group? Something like:

func _ready():
	add_to_group("generic_props")
	for n in get_tree().get_nodes_in_group("generic_props"):
		n.connect("body_entered", _on_body_entered)

Would that work? Or is there a simpler way?

Your first example makes sense, the body_entered signals is emitted when two objects collide, your RigidBody in the form of self and the other colliding body as the argument for _on_body_entered.


Could you explain why this doesn’t make sense? Did you encounter an error?

the printed statement isn’t being output when two objects sharing this script collide, so I assume the signal isn’t set up like I intended.

I see no other errors.

I can see the two objects happily colliding with each other in the physics engine, so I don’t think it’s an issue with collision layers etc…

RigidBodies need contact monitoring enabled at contact reports set greater than 0, were those properties enabled?

Thanks! Missed the contact reports

I’m pleased my first instinct for how to do this was right, disappointed how quickly I assumed my code didn’t make sense :sweat_smile:

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