Player moves into enemy territory and enemy follows?

So, I’m trying to create and enemy that moves back and forth until the player moves into an area2d and the enemy begins to follow the player- I tried attaching an area 2d to the enemy but I realized I don’t want the area 2d to move with the player as I’m creating a maze game and I don’t want the area 2d to go through walls and cause glitches if the player is in the area 2d but on the other side of the way. For now I have the area 2d as a sibling of the enemy in the main scene- but I’m not sure how I would connect that to the enemy so that it can monitor the player and track the player. any tips of how to create this behaviour in an enemy? Screen shot of how the level scene is set up attached!

Use signals. You can keep the enemy territory as a sibling - make signals entered to and exited and connect them to itself (as in both of the signals from enemy territory connected to enemy territory). Make the enemy territory mask detect only the player. Create var player that you’ll signal, for func entered(body): player = body and for func exited(body): player = null and use signal of player in enemy code, here’s a cheat code:

Alternatively you can do the same thing in area2d as before but instead of signal player just make a variable player and use get_parent().get_node(node) tho most would recomend learning and using signals.

This is very helpful! Just one quick question- what do you mean by using the signal of the player in enemy code?

Sorry, I’m pretty new at this stuff! thanks in advance

In the area2d you’d need to setup player_entered.emit(player) - so it would emit player_entered signal anytime the player variable changes now in the world node you’d setup a func that connects both so func _ready(): $enemyterritory.player_entered.connect($“enemiesnodename”.“functon in enemy scene that tells enemies to follow player)” - depends on how your code is layered out in the enemy scene.
A really good and simple instruction on how to use signals can be found here Node communication (the right way) :: Godot 4 Recipes . From there it should be easier to understand everything about signals in godots help panel. Hope it helped - there’s not a lot of video tutorials so I’d recommend starting with kids can code link I sent you and going from there. It’s crucial to undarstand it yourself as the more complicated your game gets the more you’ll find yourself needing to setup custom signals. Of course one can try to setup node hierarchy certain way but as you can see it’s not always viable.

Thank you so much! And yes I’ll definitely read up because I didn’t know that you could do that kind of thing with signals

1 Like