Problems with signal
Asked Answered
P

3

0

Hey, guys,

I'm working on a predator-prey simulation for a school project.

The predator and prey nodes have a 2D area attached to them. If the predator's area touches the prey's area, the prey dies. For the reproduction simulation, I create instances of predators and prey every 1 second.

However, when I send the signal to delete the prey, only the original prey is deleted. The other instances seem to "ignore" the command.

Here is my code:

Predator script:

func _on_area_2d_area_entered(area):
if area.is_in_group("presas"):
print("O caçador encontrou uma presa")
hunt.emit()

Prey script

func _on_predador_hunt():
queue_free()

Presumable answered 1/12, 2023 at 12:46 Comment(0)
F
1

Presumable If predator emits "hunt" signal then the signal should be connected to a signal handler in the level node, not in prey node because you don't know which prey the predator will catch.

If you don't fully understand how signals work, I suggest going through introductory Your first 2D game tutorial in the official docs.

Francie answered 1/12, 2023 at 20:59 Comment(0)
F
0

Presumable You need to connect the signal to _on_predator_hunt() for every new instance using connect() method.

Francie answered 1/12, 2023 at 13:49 Comment(0)
P
0

Francie Can you help me with that? I'm not familiarized with connect method.

I have a script attached to my level node that controls the spawn of predators and preys and tried to use the connect method

...

func _on_prey_reproduction(pos):
var prey = prey_scene.instantiate()
prey.position = pos
$preys.add_child(prey)
preys.append(prey)
prey.connect("hunt", on_predator_hunt)

...

But when I execute the code:
E 0:00:03:0214 level.gd:31 @ on_prey_reproduction(): In Object of type 'CharacterBody2D': Attempt to connect nonexistent signal 'hunt' to callable 'CharacterBody2D(prey.gd)::on_predador_hunt'.

Presumable answered 1/12, 2023 at 20:1 Comment(0)
F
1

Presumable If predator emits "hunt" signal then the signal should be connected to a signal handler in the level node, not in prey node because you don't know which prey the predator will catch.

If you don't fully understand how signals work, I suggest going through introductory Your first 2D game tutorial in the official docs.

Francie answered 1/12, 2023 at 20:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.