Godot 4: How to cast a ray from mouse_position, towards camera orientation in 3D?

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

I am having a lot of trouble with raycasts in Godot 4, considering how they’ve changed. Now there’s a raycast node, but i’m trying to do this within code.

I want to be able to cast a ray from the mouse position in the camera viewport (current), to the mouse position in world space (i.e when my mouse is over a box), how can I accomplish this?

For reference, i’m looking at this but the documentation is outdated.

:bust_in_silhouette: Reply From: Olaf

This works for me in Godot4:

var mouse_pos = get_viewport().get_mouse_position()
var ray_length = 100
var from = camera.project_ray_origin(mouse_pos)
var to = from + camera.project_ray_normal(mouse_pos) * ray_length
var space = get_world_3d().direct_space_state
var ray_query = PhysicsRayQueryParameters3D.new()
ray_query.from = from
ray_query.to = to
ray_query.collide_with_areas = true
raycast_result = space.intersect_ray(ray_query)
3 Likes