0 votes

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.

Godot version 3.2.3.stable
in Engine by (12 points)

2 Answers

0 votes

When body or area enters another area it makes it emit signal onbody or onarea 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 onareaentered( node ) :
if node.team == "blue"

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

by (5,643 points)
0 votes


func my_click_function():
    var player_area = get_node("NodePath_to_player/AttackRange")
    if player_area.overlaps_body(self):
by (4,982 points)

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")

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

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.