Topic was automatically imported from the old Question2Answer platform.
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?
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)