Hi, I'd like more information on how RayCast2d works. I'm currently working on a script for AI's in a 2d platformer, they emit raycasts to the player in their field of view, however I need to know if the ray collides with my tilemap before it reaches the player. On all the tutorials I've seen the developer retrieve an "Object" with the GetCollider() function and then use IsInGroup() or GetName(). Except that these functions are not present in the Object class. Could you tell me more about this? At the moment I use 2 raycasts with 2 different layer Mask to know if there is a collision with my tilemap.
How to know what RayCast2d IsColliding ?
Are you raycasting directly using the direct space state (like in this page on the documentation) or are you using Raycast2D nodes?
If you are raycasting directly using direct space state, there are a couple of ways you can determine what you are raycasting with. Here are a few ways you can do it:
var result = space_state.intersect_ray(origin_position, end_position)
if result:
# Check using the name:
if result["collider"].name == "TileMap":
print ("Hit tilemap!")
# Check using a group
if result["collider"].is_in_group("Group_TileMap") == true:
print ("Hit tilemap!")
# Check if what you hit is of the tilemap type
if result["collider"] is Tilemap:
print ("Hit tilemap")
If you are raycasting using the Raycast2D node, then you can use the following code to detect if you are colliding, get the object you are colliding with, and then determine if it is a tilemap:
var raycast_node = get_node("Raycast2D")
if raycast_node.is_colliding():
var object_collided_with = raycast_node.get_collider()
# Check using the name:
if object_collided_with .name == "TileMap":
print ("Hit tilemap!")
# Check using a group
if object_collided_with .is_in_group("Group_TileMap") == true:
print ("Hit tilemap!")
# Check if what you hit is of the tilemap type
if object_collided_with is Tilemap:
print ("Hit tilemap")
Also: Welcome to the forums!
Thank you :) I am using a RayCast2d node but your code using Godot Script and I'm using C#. In the documentation I saw that RayCast2d_Node.GetCollider() return a Object class and Object class does not contain a methods or members for get name or groups. Can you confirm this ?
I am fairly sure you are right, that the Object
class does not contain methods or members for the functions I listed above, because the functions are defined as part of Node
(if I recall correctly). You likely will need to attempt to cast the Object
to a Node
, which should be possible because the Node
class extends the Object
class. Code like the following should work, though I have not tested it:
Object other_collided_with = raycast_node.get_collider();
Node other_collided_with_node = (Node)other_collided_with;
if (other_collided_with_node != null):
// Perform conditions here!
The documentation on C# scripting in Godot looks like it also covers how to handle casting in C# with Godot.