Raycast2D not working when inside Node2D

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

Hi! I’m having problems when trying to use Raycast2D inside a Node2D. If I put the Raycast2D directly as a child of my KinematicBody2D do this:

func _print_raycast_check():
	if raycastCheck.is_colliding():
		print("Is colliding")

, it works fine. But if I put the Raycast2d inside a Node2D as in KinematicBody2D => Node2d => Raycast2D, and do:

func _print_raycast_check():
        for raycast in Node2d.get_children():
	        if raycastCheck.is_colliding():
		       print("Is colliding")

, then it doesn’t work anymore. Also, while using this code sometimes I get an error message saying nonexistent function ‘get_children’ in base ‘Node2D’, but not consitently.

Am I missing something here?

Thanks in advance!

I’m curious as to why you’re calling your collision check for the raycast inside of a loop. Do you have multiple raycasts that you want to perform checks on?

l.riehl | 2020-07-05 15:57

:bust_in_silhouette: Reply From: theeaglecometh

Not sure if this is just a typo but “Node2d.get_children():” should be “$Node2d.get_children():”

I would also name it something other than Node2D to avoid confusion with the built in type maybe “RaycastHolder”

Also your for loop is indexing with raycast not raycastCheck.

My suggestion:

func _print_raycast_check():
        for raycastCheck in $RaycastHolder.get_children():
            if raycastCheck.has_method("is_colliding"): #catch exceptions
                if raycastCheck.is_colliding():
                   print("Is colliding")

Ey @theeaglecometh! Thanks for your reply. I solved it, the problem was that I was using the wrong onready var. Instead of calling the Node2 and then doing .get_children(), I was calling Node2D/Raycast2D and then calling .get_children(), but obviously Raycast2D didn’t have any children :smiley:

You are right about the names. I was using those just for reference here, but I have everything named more concisely and descriptively in my project.

Thanks again!

li_fran | 2020-07-06 16:15