three.js 选中物体

实现功能:

1.选中物体,高亮显示,并设置为旋转控制中心与视口中心;

2.选中下一个物体,上个物体选中效果恢复;

3.按ESC键退出

代码:

//【事件】-单击click,执行
			//1.1s内无鼠标拖拽,再执行:构件选中函数onDocumentMouseClick1();
			//2.1s内鼠标拖拽,执行:旋转定位函数、并以构件中心旋转
			//【函数】点击选中构件
			var zu1 = [];
			var zu2 = [];
			function onDocumentMouseClick1(event) {
				var vector = new THREE.Vector3((event.clientX / window.innerWidth) * 2 - 1, -(event.clientY / window.innerHeight) * 2 + 1, 0.5);
				vector = vector.unproject(camera);//用摄像机的投影矩阵解压矢量
				var raycaster = new THREE.Raycaster(camera.position, vector.sub(camera.position).normalize());
				var intersects = raycaster.intersectObjects(scene.children);
				//console.log(zu1);
				//console.log(zu2);
				if (zu1.length == 0) {
					if (intersects.length > 0) {
						zu2.push(intersects[0].object.material.clone());//存储材质
						//console.log(intersects);
						orbitControls.target = intersects[0].point;//选中构件设置为旋转中心(置于控制器视角中心)
						intersects[0].object.material.color = new THREE.Color(0x00CED1);//选中构件设置为深绿宝石
						//intersects[0].object.material.depthTest=false;//关闭深度测试
						intersects[0].object.material.transparent = true;
						intersects[0].object.material.opacity = 0.5;
						zu1.push(intersects[0].object);//存储对象
					};
				}
				else {
					zu1[zu1.length - 1].material = zu2[zu2.length - 1];
					if (intersects.length > 0) {
						zu1.pop();
						zu2.pop();
						zu2.push(intersects[0].object.material.clone());//存储材质
						//console.log(intersects);
						orbitControls.target = intersects[0].point;//选中构件设置为旋转中心(置于控制器视角中心)
						intersects[0].object.material.color = new THREE.Color(0x00CED1);//选中构件设置为深绿宝石
						//intersects[0].object.material.depthTest=false;//关闭深度测试
						intersects[0].object.material.transparent = true;
						intersects[0].object.material.opacity = 0.5;
						zu1.push(intersects[0].object);//存储对象
					};
				};
			}
			//ESC
			function onKeyPress(event){
				switch(event.keyCode){
					//esc
					case 27:if (zu1.length> 0){zu1[zu1.length - 1].material = zu2[zu2.length - 1]};
				};
			};
			//【监听】
			document.addEventListener('dblclick', onDocumentMouseClick1, false);//双击选中物体
			document.addEventListener('keydown',onKeyPress,false);//ESC

你可能感兴趣的:(javascript,three.js,可视化)