Godot Version
v4.2.1.stable.mono.official [b09f793f5]
Question
I have this script, which performs a raycast:
PhysicsRayQueryParameters3D query = PhysicsRayQueryParameters3D.Create(shooter.GlobalPosition, shooter.GlobalPosition + (direction * distance), 1);
var spaceState = GetWorld3D().DirectSpaceState;
var result = spaceState.IntersectRay(query);
if (result.Count > 0)
{
CharacterStatus cs = ((Node3D)result["collider"]).GetNodeOrNull<CharacterStatus>("%CharacterStatus");
if (IsInstanceValid(cs))
{
shooter.wm.OnWeaponHit(cs);
}
}
If the raycast hits something, I want to check if it is a characterbody and if it is in the “Player” group. How can I do that?
if result[collider] = CharacterBody3D and\
get_tree().get_nodes_in_group("Player").find(result[collider]) != -1:
some_function()
should work. I haven’t tested it. The backslash is important. You can see more here.
References:
1
2
3
4
It gives me the error “'‘CharacterBody3D’ is a type, which is not valid in this context” .
I’m working in C#, so it might be different than GDscript.
I don’t know c#, sorry. Some of the links might be helpful though.
I managed to find a way to check if it’s in the group using
if (!GetTree().GetNodesInGroup("Player").Contains((Node)result["collider"]))
Can’t find a way to check the collider type, but I can work around it with groups, so it’s not that bad. Still would be nice to know how to check it.
result is a dictionary, which can be searched for the colliding body. In my earlier post, I used 1 equals, where I should have used the word ‘is’. This might help a little, if you can convert to C#.
In GDScript it might be:
if is_instance_of(result[collider], CharacterBody3D):
function()
I solved it this way.
var collision = spaceState.IntersectRay(query);
var cHitObject = collision["collider"];
if(((Node)cHitObject).IsInGroup("Enemy"))
{
GD.Print("This was an enemy");
}