Hello, what I'm trying to do in the code below is to perform object detection in a 3D scene by clicking with the mouse. In other words, when you click on the location of an object, it should be selected and detected. However, in most cases, it cannot be detected. Where am I making a mistake, or what should I do?
private void SelectObjx(Vector2 mousePos)
{
Node collidedObject = new();
//Viewport viewport = GetViewport();
//Vector3 rayorigin = viewport.GetCamera3D().ProjectRayOrigin(mousePos);
//Vector3 raydirection = viewport.GetCamera3D().ProjectLocalRayNormal(mousePos);
var cam = (Camera3D)GetParent().GetNode("Camera3D");
Vector3 rayorigin = cam.ProjectRayOrigin(mousePos);
Vector3 raydirection = cam.ProjectLocalRayNormal(mousePos);
var spaceState = GetWorld3D().DirectSpaceState;
var query = PhysicsRayQueryParameters3D.Create(rayorigin, rayorigin + raydirection * 1000);
var intersectResult = spaceState.IntersectRay(query);
if (intersectResult.ContainsKey("collider"))
{
collidedObject = (Node)intersectResult["collider"];
GD.Print("find");
}
}