0 votes

2D game
I have an instance and this instance's root node has children. I want to do something if a specific child of the instance collides with my object.

asked Jun 22 in Engine by MaaaxiKing (291 points)

You'll have to be a lot more specific about the setup. What kinds of nodes? What kinds of collision? Are you talking about a body with multiple collision shapes?

I have an attacking object in my game scene. The attacking object is a RigidBody2D.
It has it's own scene, so it's instanced in the game's scene. Also I instanced the Player scene in the game scene. It is a KinematicBody2D. The player is made of multiple body parts. Legs, Head etc. and they have their own collision shapes. If the player is hit on the head (if the player's head is hit) by the attacking object it should play a sound, if the legs are hit, it should play another sound.

1 Answer

0 votes
Best answer

When your RigidBody2D collides with the player, information about the colliding object can be obtained in _integrate_forces(). To find out which shape of the player you collided with, you can use get_contact_collider_shape().

See:
https://docs.godotengine.org/en/3.2/classes/class_rigidbody2d.html
and
https://docs.godotengine.org/en/3.2/classes/class_physics2ddirectbodystate.html#class-physics2ddirectbodystate

answered Jun 23 by kidscancode (17,016 points)
selected Jun 24 by MaaaxiKing
extends RigidBody2D

func _process(delta):
    var bodies = get_colliding_bodies()
    for body in bodies:
        if body.name == "Player":
            if body.get_contact_collider().name == "Head":
                $AudioStreamPlayer.play()
            else:
                #do something different

Crash, I can't get any further.

First of all "crash" means there was an error message. That is useful information.

Second, get_contact_collider() is not a function on the player, so that's not going to work.

get_contact_collider_shape(), as I linked you above, is a method of Physics2DDirectBodyState, which you have access to in _integrate_forces(). You shouldn't be trying to do physics-related stuff in _process() anyway.

Alternatively, you likely could get what you want using the RigidBody2D's body_shape_entered signal, which will tell you the colliding shape information. Either way will get you the colliding shape.

Sorry dude, I was just a little bit tired. Why should I use body_shape_entered instead of body_entered()?

Because your original question said you wanted to know which shape of the body you hit.

I connected the signal body_shape_entered(body_id: int, body: Node, body_shape: int, local_shape: int). As I've said I want to check for the name of the shape. But body_shape is an integer.

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.