How to determine which collisionshape a raycast collided with

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

I have a StaticBody with a texture that contains a menu. I have created a CollisionShape (a Box) for each selection on the menu. I have a pointer implemented as a raycast which returns the selected object, but the collision it returns is always the StaticBody that contains the CollisionShape.

I want to know which CollisionShape the raycast collided with, but the raycast doesn’t seem to have such a method. Does anyone have any suggestions?

:bust_in_silhouette: Reply From: umma

Ensure raycast isn’t colliding with the static body

To get the collisions, you could try

Func _process(_delta):
  if $raycast.is_colliding():
    var collision = $raycast.get_collider()
    print(collision.body.name)

I don’t have Godot at the moment and I haven’t used it in a while so this maybe incorrect, try adjusting it a little to suit your needs.

:bust_in_silhouette: Reply From: stormreaver

The solution turns out to be rather simple and straightforward. For each selectable menu item, I created a StaticBody that is nothing but a container for its CollisionShape. The CollisionShape encompasses just the relevant menu item.

When the collision is reported, the collider will be that of the CollisionShape’s parent (the StaticBody). I can then get the StaticBody’s name with collider.get_name(). Then I just have a match statement for all the possibilities.