How can I get the scene tree node hit by a ray cast

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

I have taken the demo code from Ray-casting — Godot Engine (stable) documentation in English and am trying to use it to figure out which node in the scene tree my Oculus Quest controller is pointing at.

var offset = Vector3(0,0,-100)
var space_state = get_world().direct_space_state
var xform = controller_node.global_transform
var start:Vector3 = xform.xform(Vector3(0,0,0))
var end = xform.xform(offset)
var result:Dictionary = space_state.intersect_ray(start, end)		
var rid = result["collider"]

typeof(rid) == 17, so it is an RID. I do not know how to get a Node from the RID, so I can not modify the node.

How can I find the first Node struck by an arbitrary ray?

:bust_in_silhouette: Reply From: jgodfrey

According to the docs, 17 is TYPE_OBJECT (as expected in your described case). A TYPE_RID is 16. Also, note the Dictionary that’s returned contains a separaterid key, which should hold the RID value…

(search the above for TYPE_RID).

Yup, a quick test shows that result[“collider”] does indeed hold a reference to the intersecting body

func _ready():
  var space_state = get_world().direct_space_state
  var result = space_state.intersect_ray(Vector3.ZERO, Vector3(5,0,0))
  var collider = result.collider

prints StaticBody:[StaticBody:1264]

Haydoggo | 2023-01-23 21:57