Please help with raycast, mouse position

Godot Version

Godot 4.2.1

Question

Hello! Another question on raycasting/interaction. I want to implement an action when a mouse cursor to hover/click on a sprite3d/object. I want controls and script be attached to a camera3d. Taking Danganronpa room examination as a reference.

My clean try example for your convenience on Git
Unfo all tutorials on youtube i found are not clean enough or outdated. I tried to do it on my own and added debbug function with help of gpt. It says that no object detected while the code is alright. Here i stuck.

Mb I miss something or missunderstand it fundamentally? I see there is a RayCast3D node, what is it for? What’s the difference with other method i do? I appologies for being dumb, i really want to understand. I can make a youtube video when i figure it out afterward.

Do you know about physics picking?
It’s a way to get interactions between the mouse cursor and the 3D-world.
You could use CollisionObject3D._input_event() to get notified about mouse input events on collision objects without having to manually do a raycast.

1 Like

I see now… thank you!

Thats appeared to be unexpectedly easy.
Just like that and connect signal. Still will be good to understand manual thing, next step.

extends Area3D

func _on_input_event(_camera, event, _position, _normal, _shape_idx):
	if event is InputEventMouseButton:
		if event.pressed:
			print("Horay!")

func _on_mouse_entered():
	print("Mouse enter on: ", self.name)

I can’t understand why this not working.

# this to activate raycast
func _input(event): 
	if event.is_action_pressed("left_click"):
		shoot_ray()

func shoot_ray():
# here we tell where to raycast is pointing adn from where
	var mouse_pos = get_viewport().get_mouse_position() 
	var ray_length = 1000
	var from = project_ray_origin(mouse_pos)
	var to = from + project_ray_normal(mouse_pos) * ray_length
	var space_state = get_world_3d().direct_space_state

# here i set params for intersect_ray
	var params = PhysicsRayQueryParameters3D.new()
	params.from = from
	params.to = to
	params.collide_with_areas = true  # Set to true to include Area nodes
	params.collide_with_bodies = true  # Set to true to include PhysicsBody nodes (don't know if necessary)

	var result = space_state.intersect_ray(params)

# here I try to see the result
	if result and result.collider and result.collider.is_class("Area3D"):
		result.collider.on_ray_hit()
	else: 
		print("Raycast hit:", result.collider.name)

Unfortunately even “Else” clause not returning a result. What did i miss -_- ?

Well one of the branches of the if statement has to do something :slight_smile: If not then make sure shoot_ray() is actually called. And that on_ray_hit() works properly whatever it’s supposed to do. The raycast code itself works for me.

Oh, god. It was not detecting my mac touchpad. This was the issue. Now all set. Thanks)