Need help with selecting objects using Raycaster.intersectObjects

First time using the raycaster and new to 3d as well… I’m trying to understand how to make item selection in my scene work. Here’s a sample scene and below the code that tries to find the selected from mousedown event…

EXPECTED

My goal is to be able to select any item in the scene from any camera angle. Including clicking on the top of the Box items and if only a tiny portion of a Box is visible / occluded, I’d still like to be able to click on an item and select it…

RESULT
Often I get no items in my intersection array. Even clicking on different Y axis values (clicking near the top of the item or near the middle/bottom) yields sometimes an item found and other times no items found…

Thanks

    OnClick(event)
    {
        //event.preventDefault();
		
		var coordX = event.offsetX < 0 ? 0: event.offsetX;
		var coordY = event.offsetY < 0 ? 0: event.offsetY; 
		console.log("ControllerSelection: listening to mouse click event - X:"+coordX+",Y:"+coordY);
        this.Mouse.x = ( coordX / window.innerWidth ) * 2 - 1;
        this.Mouse.y = - ( coordY / window.innerHeight ) * 2 + 1;

		// Get item ID from selection
		// Fire item selected event with ID
		this.Raycaster.setFromCamera(this.Mouse, this.ModelScene.Camera);
		const intersection = this.Raycaster.intersectObjects(this.ModelScene.Scene.children, true);
		if (intersection && intersection.length > 0 ) 
		{
			var item = intersection[0].object;
			if (item && item.MyId)
			{
				console.log("ControllerSelection: OnClick selected item ID - " + item.MyId)
			}
		}
    }

Was using the wrong source element to derive my coordinates… I have a desktop app with a typical sideBar, content area (3d), prop editor layout and so my THREE canvas is not full window viewport, it’s constrained in the middle of my viewport…

This seems to be working…

		var coordX = event.offsetX < 0 ? 0: event.offsetX;
		var coordY = event.offsetY < 0 ? 0: event.offsetY; 
		console.log("ControllerSelection: listening to mouse click event - X:"+coordX+",Y:"+coordY);
		const widthHalf = this.ModelScene.Container.clientWidth * 0.5;
		const heightHalf = this.ModelScene.Container.clientHeight * 0.5;
		this.Mouse.x = (coordX- widthHalf) / widthHalf;
		this.Mouse.y = - (coordY - heightHalf) / heightHalf;
1 Like