I'm trying to figure out how to do this in godot 4.

So far it's not working, a new pair of eyes might find the issue

var raycast_length = 1000
	var space_state = get_world_3d().get_direct_space_state()
	var mouse_position = get_viewport().get_mouse_position()
	var params = PhysicsRayQueryParameters3D.new()
	params.from = camera.project_ray_origin(mouse_position)
	params.to = params.from + camera.project_ray_origin(mouse_position) * raycast_length
	params.collision_mask = 1
	var result = space_state.intersect_ray(params)
	if result:
		print("colliding!")
		mouse_select.global_transform.position = result.global_transform.origin

PS:There is no error, it just doesn't print anything.

  • xyz replied to this.
  • Loxyrak 'to' point is calculated by adding the ray direction vector to the 'from' point, not ray origin again. So you should use camera.project_ray_normal() when calculating 'to' point.

    Loxyrak 'to' point is calculated by adding the ray direction vector to the 'from' point, not ray origin again. So you should use camera.project_ray_normal() when calculating 'to' point.

    Here is the raycast function I am using for my 3D mouse click raycast in godot 4.0, hope this helps:

    func raycast_from_mouse(m_pos, collision_mask):
    	var ray_start = cam.project_ray_origin(m_pos)
    	var ray_end = ray_start + cam.project_ray_normal(m_pos) * ray_length
    	var world3d : World3D = get_world_3d()
    	var space_state = world3d.direct_space_state
    	
    	if space_state == null:
    		return
    	
    	var query = PhysicsRayQueryParameters3D.create(ray_start, ray_end, collision_mask)
    	query.collide_with_areas = true
    	
    	return space_state.intersect_ray(query)
    7 months later

    Hi all,
    Hope it's okay to add to this. I was looking at writing this in C# and I noticed there is no example there. Is that because the C# side is missing functions that are required to get that working?

    Thanks,
    Pete

    • xyz replied to this.

      I had trouble with - cam.project_ray_origin(mousepos)
      Also I'm not sure about get_world_3d() is this an equivalent - var world3D = GetViewport().World3D?

      • xyz replied to this.

        Petey Camera3D::ProjectRayOrigin() exists. Make sure you cast to proper type if you're acquiring the reference via GetNode(). And yeah GetViewport().World3D is ok.

        Ahh that's it, I wasn't casting to the camera node 🙄
        Thanks for the help 🙂