The exceptions section of a raycast 2D query in C#

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

I’m just attempting to write a simple raycasting query. However, it won’t run due to an error cropping up from: ‘new object {this}’. I know that this is really simple in GDscript but I’m trying to learn C# and I can’t seem to find this documented anywhere.

public override void _PhysicsProcess(float delta)
{
    var spaceState = GetWorld2d().DirectSpaceState;
    var result = spaceState.IntersectRay(Position, GetParent().GetNode<KinematicBody2D>("Player").Position, new object[] { this });
    if (result.Count > 0)
    {
        GD.Print("Hit at point: ", result["position"]);
    }
}

‘this’ is a KinematicBody2D element. The error I receive is: ‘object cannot be converted to type Godot.collisions.array’.
-Many Thanks

:bust_in_silhouette: Reply From: jgodfrey

You don’t show (or even say) what the reported error is - that’d be helpful…

While I haven’t tried this, the Raycasting docs seem fairly clear here:

First, only the first 2 args (the 2 Vector2 args) are required in the IntersectRay call. That 3rd arg is an exclusion array, which defines objects that the ray could collide with, but you’re not interested in knowing about.

The syntax you show for that 3rd arg looks correct, so I can only assume that maybe the object with the script (the one represented by this) isn’t a type of collision object?

It sounds like that’s necessary from the docs.

So, I’d recommend a few things:

  • See if it works without the 3rd exclusion array arg
  • If you need that 3rd arg, make sure the script is attached to a collision object
  • If you’re still struggling, post the actual error you’re seeing

Thank you for your answer, I’ve now added the error I’m receiving. However, I also tried the same general syntax but replacing this with:

GetNode<CollisionShape2D>(“Scrapper”)

and received the same error.

BinaryLies | 2020-02-06 06:48

:bust_in_silhouette: Reply From: 8bitbadger

Ok so I got it working, I was struggling with it as well hope this helps I see the thread is a bit old, I used this method

KinematicBody2D tankBody;
tankBody = GetNode<KinematicBody2D>("../../../../Player");
Godot.Collections.Dictionary hits = worldState.IntersectRay(GlobalPosition, GetGlobalMousePosition(),  new Godot.Collections.Array{tankBody}, tankBody.CollisionMask);

I hope this helps.