Check enemy in range using Area2D

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By chris3spice

I have an Area2D (“AttackRange”) for my Player and I have an Area2D (“ClickArea”) on my enemy.

I want to be able to click on the enemy when the player is withing range.
I have it to where I can click on the enemy as long as he is on screen.
I’m not sure how to do the checking that the specific enemy is withing the Area2D collision of my player.

My click function is on the enemy, so I don’t know how pass the player is in range to the enemy. to check that it is in range and also clicked for that specific enemy.

Note: I put the Area2D on the player so there is just one checking distance instead of each enemy checking distance and also have a click box area.

:bust_in_silhouette: Reply From: Inces

When body or area enters another area it makes it emit signal on_body or on_area entered. You can use it to mark clickable objects. This signal intakes one argument, which is the exact object that entered the area. Thanks to this You can make cetrain conditions like:

func on_area_entered( node ) :
if == “blue”

And so on. There is also get_overlapping_bodies()(or areas()) function that You can call anytime to know all the bodies or areas currently being in range of collision shape

:bust_in_silhouette: Reply From: Wakatta

func my_click_function():
    var player_area = get_node("NodePath_to_player/AttackRange")
    if player_area.overlaps_body(self):

I put this code on the ClickArea since the click area will be different for each enemy. I now have this code after messing around and trying to get it working on my own and more googling. problem is even when I know they are overlapping it never prints the “in range” I tried messing around with the collision layers and everything and couldn’t get it working.

func _on_ClickArea_input_event(viewport, event, shape_idx):
     if mouse_over and event is InputEventMouseButton:
          if event.is_pressed():
               var player_area = get_node("/root/Level/Player/AttackRange")
               if player_area.overlaps_body(self):
                     print("in range")

chris3spice | 2021-03-19 11:05

overlaps_body() expects your enemy (the ‘self’ in this case) to be a CollisionObject2D / PhysicBody2D
Even knowing this I sometimes forget. So make sure to set/extend your enemy to types( KinematicBody2D, RigidBody2D or StaticBody2D) or use overlaps_area(self) since your code is placed in the click “area” of your enemies

Wakatta | 2021-03-20 06:48