Raycast from screen mouse postion is scale offset

Godot Version

4.6

Question

I'm currently making a lightgun/rail-shooter. For that purpose I need to cast a ray from the position the mouse pointer is at. I am using the technique described in the manual for raycasting at the bottom of the page:

const RAY_LENGTH = 1000.0

func _input(event):
	if event is InputEventMouseButton and event.pressed and event.button_index == 1:
		var camera3d = $Camera3D
		var from = camera3d.project_ray_origin(event.position)
		var to = from + camera3d.project_ray_normal(event.position) * RAY_LENGTH

I am just using “project_local_ray_normal()” instead so the raycast takes the camera position and rotation into account. So far, this has worked very well for me. I have made 2 small games with this and they worked pretty much flawlessly.

For my newest project however, the ray is offset from the mouse position. The offset seems similar to scaling at first, with the offset being 0 at the center of the screen and getting stronger the closer to the corners. II tried to solve the issue by just scaling the cursor position accordingly, but this has the issue that changing the resolution will change the offset scale. It also seems like it’s not just a scaling issue as taking it into account there is now a small offset strongest when around 1/3rd from the center of the screen.

I have no idea what the reason for this issue could be. I have set up pretty much everything the exact same as my previous projects, aside from setting up the project in a newer Godot version. If anyone has any idea what could cause this issue I’d be really grateful!

I think I might have solved it:

var from: Vector3 = camera_3d.global_position
var to: Vector3 = camera_3d.project_ray_normal(pos) * RAY_LENGTH

ray_cast_3d.global_position = from
ray_cast_3d.target_position = to
ray_cast_3d.force_raycast_update()

if ray_cast_3d.is_colliding():

while setting the raycast to “top level”.

The code listed in the docs has the issue that it will not take into account camera movement/turns, so it was somewhere suggested to change “camera_3d.project_ray_normal” to “camera_3d.project_local_ray_normal” . This seems to mostly work but it causes some inconsistent behavior like offset. Indeed, in my previous project I had to slightly offset the cursor vertically and assumed that was just a godot bug that would eventually get fixed.

I have changed it now to this new solution and the offset is gone there as well. It seems that the “scaling issue” in my current project was actually also just an offset, just in camera z direction.

Maybe someone could take a quick look anyway and tell me whether this makes sense or not, my brain is kinda telling me “it can’t be that easy” and “I’m probably overlooking something here”.