collision-detectiongodotgodot4

How can I check for the child instead of the parent for collision in Godot?


I'm trying to detect collision to attack an enemy, but I don't want it to detect the player as a whole, I just want it to detect the Collision2D node named "Sword Hitbox". Is there any way to make it detect that?

For reference here is the code that works for detecting anything to do with the player (including the node that I want it to only work for):

func _on_body_entered(body: Node2D) -> void:
    if body.name == "Player":
        print("Detected")

I tried just saying "Sword Hitbox" where I have "Player" written, but that doesn't work, it just makes it so that nothing can touch the enemy.


Solution

  • The great part about game engines are that there are many ways to do a task, and this is no different. In your case, the best approach is likely to be the use of collision layers/masks, but note that you could also filter detections in your scripts, or through filtering signals.

    In Godot, collision layers separate all of your different collision shapes into distinct bins. For example, you may want terrain to be one type of collision, entities another, etc. These bins are called layers.

    Objects can have their collision layer and collision mask defined. An object's collision layer tells it which of those bins(layers) it will live in, and its mask tells us which layers it will scan for collisions.

    In order to have an enemy detect collisions with just your attacks, you could put your attack collision shapes onto their own collision layer, and set the enemy to only see that layer through its collision mask. These can be set in the editor by inspecting the node.

    For more information, see the documentation here: https://docs.godotengine.org/en/stable/tutorials/physics/physics_introduction.html#collision-layers-and-masks

    Edit:

    You may need to have your various hit-boxes separated into different sprites/collision shapes in order to use this approach. (See OP comment below)