How to cast a ray in 3D space?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By unfa
:warning: Old Version Published before Godot 3 was released.

I’m trying to cast a ray from object to current camera, but I never get any collision.

I have a Sprite3D object that has a RayCast child. It always returns false for is_colliding() method. What am I doing wrong?

extends Sprite3D

func _ready():
	set_process(true)
	
func _process(delta):
	var ray = get_node("RayCast")
	var camera_pos = get_tree().get_root().get_camera().get_global_transform().origin
	ray.set_cast_to(camera_pos)
    print(ray.is_colliding())


	
:bust_in_silhouette: Reply From: unfa

Make sure to used _fixed_process instead of +process, otherwise the direct_space_state() won’t be accessible, and will return null, resulting in an error.

extends Sprite3D

func _ready():
	set_fixed_process(true)
	
func _fixed_process(delta):
	var camera_pos = get_tree().get_root().get_camera().get_global_transform().origin
	var halo_pos = get_global_transform().origin
	
	var ray = get_world().get_direct_space_state().intersect_ray(halo_pos, camera_pos)
	if(ray.empty()):
		show()
	else:
		hide()