I met a strange problem about ray-casting in godot

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

I wantt to use the ray-casting to get the cursor position on a plane to make a ball roll to the position. But I found that ray-casting could not identity the correct position. So I added an ImmediateGeometry node to draw the rays in the world to check what happened. Here is what I found:Image

The origin of camera is infront of my view port and the rays are obviously not correct for usage because their origins are even infront of my cursor! I don’t know why it happens, and here is my code:

	if event is InputEventMouseButton and event.button_index == BUTTON_LEFT and event.is_pressed():
	if Input.get_mouse_mode()==Input.MOUSE_MODE_VISIBLE:
		var from=project_ray_origin(event.position)
		var to=from+project_ray_normal(event.position)
		G.begin(PrimitiveMesh.PRIMITIVE_LINES)
		G.add_vertex(from)
		G.add_vertex(to)
		G.end()

It’s very strange, I also tried to move and create some other rays from another origin. In short, whereever I am I can always rotate my camera and see the origin of my camera. It is like you can rotate your eyes 180 degrees to see your brain. And because of this, what is shown in the viewport is not coincide the real camera position.

:bust_in_silhouette: Reply From: Andrea

i cant see the picture because this forum does not let you, but if you want the ray to start from the camera, use $Camera.global_translation as the starting point, and $Camera.project_position(screen_coordinate, distance) as final point