Why does this raycast script not work on the rigidbody?

Godot Version

Godot 4.5

Question

In a scene with a StaticBody3D, a RigidBody3D (gravity scale 0), camera, light source, and a node parent to both the Bodies why is this script not detecting the RigidBody3D when clicked? Instead it is only working on the StaticBody. Both Bodies have collisions and matching primitive mesh, the rigid is smaller but closer to the camera than the static.

extends Node3D

var screen_size : Vector2

var box_dragging : Variant = null

var mouse : Vector2 = Vector2()
const DIST : int = 1000

var exclude_list : Array
var plane_exclude : Array

func _input(event : Variant) -> void:
	if event is InputEventMouseButton and event.button_index == MOUSE_BUTTON_LEFT:
		if event.pressed:
			print('CLICK')
			var box_collider : Variant = raycast_check_for_box_3d(mouse)
			if box_collider:
				box_dragging = box_collider
		else:
			box_dragging = null
			print('RELEASED')


#Checks for boxes
@warning_ignore("shadowed_variable")
func raycast_check_for_box_3d(mouse : Vector2) -> Variant:
	var space_state : PhysicsDirectSpaceState3D = get_world_3d().direct_space_state
	
	var start : Vector3 = get_viewport().get_camera_3d().project_ray_origin(mouse)
	var end : Vector3 = get_viewport().get_camera_3d().project_position(mouse, DIST)
	
	var box_params : PhysicsRayQueryParameters3D = PhysicsRayQueryParameters3D.new()
	box_params.from = start
	box_params.to = end
	
	var box_result : Dictionary = space_state.intersect_ray(box_params)
	print(box_result)
	if (box_result.size() > 0):
		print(box_result.rid)
		return box_result
	else:
		return null

# Called when the node enters the scene tree for the first time.
func _ready() -> void:
	screen_size = get_viewport().get_visible_rect().size

Check the documentation about ray-casting:

WOW! THANKS, MR. /s

1 Like

Based on your code alone without seeing your node structure, it seems like you create the mouse variable at the top of your script, but never actually update it.
So my guess is that it’s always at (0,0) coordinates, and because your StaticBody is likely much bigger than your RigidBody, it likely only hits your static body.
Update your mouse position somewhere every frame.

1 Like

(post deleted by author)

You know what, I’m going to test that a little more tomorrow and get back to you about it.

1 Like

AH HA~!

It was missing one single line of code:

mouse = event.position

2 Likes