How to detect object in a 3D scene by clicking with the mouse?
Asked Answered
R

2

0

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");
		}
	}
Rosser answered 6/11, 2023 at 1:58 Comment(0)
S
0

Rosser Ray query parameters expect from/to position to be in world space, but you're taking the ray direction in camera's local space. Instead of ProjectLocalRayNodemal() try using ProjectRayNormal() which returns the direction in world space.

Squaw answered 6/11, 2023 at 3:14 Comment(0)
R
0

Squaw Yes, it worked properly when I did as you said.thanks.

Rosser answered 6/11, 2023 at 16:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.