The Godot Q&A is currently undergoing maintenance!

Your ability to ask and answer questions is temporarily disabled. You can browse existing threads in read-only mode.

We are working on bringing this community platform back to its full functionality, stay tuned for updates. | Twitter

0 votes

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?

For reference, i'm looking at this but the documentation is outdated.

Godot version v4.0.alpha.custom_build [21c79d751]
in Engine by (41 points)

1 Answer

+1 vote

This works for me in Godot4:

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 =
ray_query.from = from = to
ray_query.collide_with_areas = true
raycast_result = space.intersect_ray(ray_query)
by (16 points)
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.