KinematicBody2D find adjacent nodes

brassharpoonerbrassharpooner Posts: 4Member
in 2D

I have a couple of KinematicBody2D nodes and am trying to detect whether they have any adjacent nodes.

Prior to Godot 3 it seems like the object had is_colliding() and get_colliders() methods, but they don't seem to be there anymore, and I'm sure whether those were what I was looking for anyway, since a collision may have happened at a given frame in the past but I'm looking for adjacent/touching nodes now.

More broadly, I'm looking for a mechanism that will tell me whether an enemy character is within range of melee attacks, which should only be the case of adjacent characters. This tutorial: shows how to create an Area2D for a weapon wielded by a character and use that to determine whether melee attacks have hit home, but I'd like to avoid having separate nodes for character and weapon at this stage.


  • brassharpoonerbrassharpooner Posts: 4Member

    So I found a solution, but it's not very elegant. I wrapped my character in an Area2D that is slightly larger than the character's CollisionShape2D node. When the enemy's body enters the area I set a can_attack flag to true, and set it to false when the enemy body exits the area.

    It does the trick, but I would still rather actually detect whether the nodes are actually adjacent/touching. I guess I could just inspect the position property for both nodes, but wondering whether Godot has something out of the box that could help here?

  • MegalomaniakMegalomaniak Posts: 826Admin
    Answer ✓

    AFAIK that's the way it's typically done. Not sure what is supposedly so inelegant about it. :/

  • brassharpoonerbrassharpooner Posts: 4Member

    Thanks Megalomaniak. Well the Area2D surrounding the character has an arbitrary size that's just slightly larger than the character, so enemy characters will get in range even if they're not strictly adjacent to the player node. But I guess that's just a question of thresholds. Anyway thanks for taking the time to reply.

  • TwistedTwiglegTwistedTwigleg Posts: 626Moderator
    Answer ✓

    @brassharpooner said:
    ... I would still rather actually detect whether the nodes are actually adjacent/touching

    You can use get_overlapping_bodies, which will return a list of all of the bodies that are overlapping/touching that area (for the most recent physics frame). Using get_overlapping_bodies may slow down performance if you use it too much, so you'll likely still want something (like another Area2D node) to tell you when to start looking for collision bodies using get_overlapping_bodies.

    Though as Megalomaniak said, using a Area2D slightly larger than the player is typically the way it's done (generally for performance reasons)

  • brassharpoonerbrassharpooner Posts: 4Member

    Thanks, I ended up using an Area2D but I'll also look into get_overlapping_bodies.

Sign In or Register to comment.