Is there a way of using multiple raycasts for one thing? I've watched this video: youtube.com/watch?v=7JCRpY3biZg&t=300s (skip to 7:25) and he makes a ground check using 3 raycasts. He does this through a 'for' loop but when I try it does nothing. Would a for loop be the most efficient way of doing this? Or is it possible to store multiple Raycasts in 1 variable? If anyone wants to see my code just say, jumping is identical to the code in the video. Thanks so much in advance.

Watching the video, I think that if you are using Raycast2D nodes, then using a for loop and returning true on the first collision is probably most efficient way. That way if the first raycast is colliding, the code will stop looping and checking the values in the other raycasts. Worse is that you loop through all the raycast nodes and none of them are colliding, which because the code within the for loop is a simple if statement, it shouldn't impact performance unless you have a lot of raycasts.

If you want potentially, slightly better performance at the cost of more complex code, you could use the DirectSpaceState2D to perform the raycasts. Then you could write the code so it sends each raycast out one at a time, only sending the next raycast if the first didn't collide. This way you could potentially improve performance very slightly since you are only sending out as many raycasts as you need. The Raycast2D nodes will (if enabled is true) send a raycast out every _physics_process call for every Raycast2D node, which technically means you are potentially doing more work then needed (since if one raycast collides, no reason to send the other raycasts)

That said, I honestly thing the performance increase would be magrinal and hardly noticable unless you have lots of Raycast2D nodes firing off all the time. I would probably just use the Raycast2D nodes with code similar to the video, as cleaner code that is easy to understand and debug is worh the very small performance loss, in my opinion.

He does this through a 'for' loop but when I try it does nothing.

Do you have the enabled property for each Raycast2D node set to true in the inspector? Also, are there objects on the collision layer(s) for the raycast to collide with?

You could use force_raycast_update (documentation) in the for loop if you don't have enabled set to true and only want the Raycast2D nodes to update when you are checking if they are colliding.


Hopefully this helps :smile:

Ahh idiot me, enabled was not set to true. Thanks, this is pretty clean. Using a DirectSpaceState seems a bit excessive for now but at some point in the future I ought to take a look. Thanks again :)

I only know to check if enabled is true by having had similar issues way too many times! Happy to help! I'm glad it works now :smile:

3 years later