0 votes

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

asked Feb 6 in Engine by BinaryLies (15 points)
edited Feb 6 by BinaryLies

2 Answers

+1 vote
Best answer

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.

answered Feb 28 by 8bitbadger (46 points)
selected Feb 28 by BinaryLies
0 votes

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:

https://docs.godotengine.org/en/latest/tutorials/physics/ray-casting.html

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
answered Feb 6 by jgodfrey (5,540 points)

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.

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.