Raycast2D: how to get the CollisionShape of the object with which it has collided?

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

I’ve a Raycast2d to check collisions and and I need to get the object that it has collided with to know the size and position of its collisionshape, but raycast.is_colliding() only gets the object (node), and if I don’t know the collisionShape node name i can’t get it.

The Scene:

Player (KinematicBody2D)
Stone (RigidBody2D)
   CollisionShape2D (CollisionShape2D)

AnotherObstacle (Area2D)
   CollisionShape2D (CollisionShape2D)


if Player.RayCastTop.IsColliding():
    var collisionShape2d = getCollisionShape2D (Player.RayCastTop.GetCollider())
    collisionShape.Height = ??
    collisionShape.Width = ??

If there any way to get the CollisionShape2D of an object returned by raycast.get_collider() ?

:bust_in_silhouette: Reply From: njamster

Nothing special about it. Assuming the CollisionShape2D is a direct child of the node the Raycast2D is colliding with, it would be as simple as this:

var collider = raycast.get_collider()
if collider:
    var collision_shape = collider.get_node("CollisionShape2D")
    # ...

If it’s not a direct child, than you need to adapt the NodePath accordingly.

What if the ennemy has for example a head and a body : how can I know if the bullet reaches the head or the body ?

cmzx | 2020-09-06 13:22

If both head and body have their own body, it works exactly the same. If they don’t (i.e. the enemy is one body with two collision shapes belonging to it), you can do:

var collider = raycast.get_collider()
if collider:
	var i = raycast.get_collider_shape()
	var hit_node = collider.shape_owner_get_owner(i)

njamster | 2020-09-06 14:33

OMG thank you ! I didn’t know you could get multiple colliders like that !!!

cmzx | 2020-09-08 19:43

Very helpful, but let me add that this only works with GodotPhysics and not with Bullet because get_collider_shape() is currently broken with Bullet.

metin | 2021-09-25 22:00

Encase somebody was confused why the shape_owner_get_owner could fails sometimes (at least when there’s lots of collision shapes in a single object) it’s due to being given the shape_id instead of the owner_id (which works most of the time but can fail sometimes) but it can be fixed by changing

var hit_node = collider.shape_owner_get_owner(i) 


var hit_node = collider.shape_owner_get_owner(collider.shape_find_owner(i))

which gives the correct id.

Stefoto | 2023-07-07 10:37