Small question about making interactable objects and 3d ray cast

Godot Version

4.4

Question

im making interactable objects and a lot of tutorials mention the raycast 3d. if im already calculating it to mark the direction my player looks at do i need to calculate the raycast 3d again or add a new one?

There is a RayCast3D node which always updates every frame and is easier to set up, then there is the intersect_ray function that runs only through code on command. I’m betting you want to use a RayCast3D in which case you do not need to use intersect_ray. If you are talking about something else, please paste some of your code, not sure how you are “calculating it to mark the direction”.

1 Like

this is part of the player code that i use to make the player look at the mouse

var ray_origin = Vector3()
var ray_end = Vector3()

func look_at_mouse():
	var mouse_position = get_viewport().get_mouse_position()
	ray_origin = camera.project_ray_origin(mouse_position)
	ray_end = ray_origin + camera.project_ray_normal(mouse_position)*2000
	var space_state = get_world_3d().direct_space_state
	var params = PhysicsRayQueryParameters3D.new()
	params.from = ray_origin
	params.to = ray_end
	var intersection = space_state.intersect_ray(params)

I remember your project now, normally I would say you could use RayCast3D, but I know you are changing cameras often so this is perfectly reasonable.

You can certainly inject interactions into this function, I would recommend storing the last hit object if it’s interactable.

var hovering_interactable: Node3D

func look_at_mouse() -> void:
	# etc ...
	var intersection: Dictionary = space_state.intersect_ray(params)

	# Check intersection for interactables
	if not intersection.is_empty():
		var collider: Object = intersection["collider"]
		# condition depends on how you define your interactables
		if collider.is_in_group("Interactable"):
			hovering_interactable = collider
1 Like

i changed it a bit and now i only use one camera tho its still changing positions a lot

Cool, if it ain’t broke don’t fix it. Does the sample make sense with your current code?

1 Like

i think, im still a bit confused as to how it works but i will try it a bit more