Godot Docs Ray Casting from Camera to Mouse Location Confusion

4.2.2

Ray Casting from Camera to Mouse Location Issue

I’ve been working on ray casting from the camera to the mouse location, following the Godot documentation. However, I’ve encountered an issue where the ray cast doesn’t line up correctly with the mouse position. Here’s what the Godot docs suggest:

Godot Docs Version

func cast_ray_from_camera():
	var mouse_pos = get_viewport().get_mouse_position()
	var from = camera.project_ray_origin(mouse_pos)
	var to = from + camera.project_ray_normal(mouse_pos) * 1000
	raycast.global_position = from
	raycast.target_position = to
	raycast.force_raycast_update()

When I use this version, the position of the ray cast is very off from where the mouse is pointing.

Without + from

func cast_ray_from_camera():
	var mouse_pos = get_viewport().get_mouse_position()
	var from = camera.project_ray_origin(mouse_pos)
	var to = camera.project_ray_normal(mouse_pos) * 1000
	raycast.global_position = from
	raycast.target_position = to
	raycast.force_raycast_update()

By removing the + from portion, I get a position that lines up correctly with where the mouse is.

My question is, am I misunderstanding the documentation, or should I just be adding + from in a different way? Any insights or clarifications would be greatly appreciated.

Because you are using a Raycast3D the target_position automatically takes into account the “from” when given “to”. I believe that documentation was written as a physics query initially, like so

var space_state := camera.get_world_3d().direct_space_state
var query := PhysicsRayQueryParameters3D.new()

var mouse_pos := get_viewport().get_mouse_position()
var from := camera.project_ray_origin(mouse_pos)
var to := from + camera.project_ray_normal(mouse_pos) * RAY_LENGTH

query.from = from
query.to = to

var result: Dictionary = space_state.intersect_ray(query)
if result.is_empty():
	print("no hit")
else:
	print(result["position"])

If yours works, then you’re good!