Get name of object/scene during collision

Godot Version

v4.2.1

Question

In my game I have ‘Squibbles’ (CharacterBody2Ds) and ‘Arrows’ and ‘Blocks’ (StaticBody2Ds). All are their own scenes with child sprites, collision shapes and raycasts. Arrows and Blocks are added to the game randomly, with multiple instances of each one.

When a Squibble collides with a Block or Arrow, I need to check which type it is (a block or an arrow). In the Squibble’s script, I’m using raycast.get_collider() to get the object it collides with, but I cannot work out how to tell what object type/scene it is…

raycast.get_collider().get_class() returns ‘StaticBody2D’ (too generic), while raycast.get_collider().get("name") returns ‘Arrow2’ (too specific). Is there another property I can check, or method I can use, that’ll return ‘Arrow’ for all arrows or ‘Block’ for all blocks?

If you have scenes for your arrow and block. I would put a class_name on each script respectively

class_name Arrow
class_name Block

Then you would check like this

If raycast.get_collider() is Arrow:
    ...
elif raycast.get_collider() is Block:
    ...

This is a class check, and will sense if it is a node with a custom script and get the class_name.

2 Likes

Thanks @pennyloafers! That did the trick. I guess I was looking for something like that already built-in, but makes sense to define the class names myself.

I generally just check the collision layer number instead, far quicker than trying to cast although I dont know if behind the hood whether it would be quicker than finding the class type.

This is highly dependant on how your collision layers are set up as well though of course. And isnt very readable in code.

1 Like

That is a good point, I think there could be some optimizations because class_names are stored globally once defined. But there probably is some object parsed script access and check penalty.

I’m on the opinion of pre-mature optimizations clutter code. I think if there is only a dozen ray casts per frame it’s not going to matter much.

Make the code simple, you can definitely make informed decisions about how you interact with data structures, but context really matters in designing code. Will I be using the method a million times a frame? I probably should, or shouldn’t, worry about optimizing…

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.