Threejs-射线拾取模型,获取模型表面点击的点坐标

     addEventListener('click',Ray);// 监听窗口鼠标单击事件
     function Ray() {
        var windowX = event.clientX;//鼠标单击位置横坐标
        var windowY = event.clientY;//鼠标单击位置纵坐标

        var x = (windowX / window.innerWidth) * 2 - 1;//标准设备横坐标
        var y = -(windowY / window.innerHeight) * 2 + 1;//标准设备纵坐标
        var standardVector = new THREE.Vector3(x, y, 0.5);//标准设备坐标
        //标准设备坐标转世界坐标
        var worldVector = standardVector.unproject(camera);
        var ray = worldVector.sub(camera.position).normalize();
        //创建射线投射器对象
        var raycaster = new THREE.Raycaster(camera.position, ray);
        //返回射线选中的对象
        var intersects = raycaster.intersectObjects(floorChildrenGroup);
        console.log(intersects);
        if (intersects.length > 0) {
            var point=intersects[0].point; //射线在模型表面拾取的点坐标
            var mesh=intersects[0].object;        
        }

    }

补充一个三维坐标转屏幕坐标

    function transPosition(position) {

        let world_vector = new THREE.Vector3(position.x, position.y, position.z);
        let vector = world_vector.project(camera);
        let halfWidth = window.innerWidth / 2,
            halfHeight = window.innerHeight / 2;
        return {
            x: Math.round(vector.x * halfWidth + halfWidth),
            y: Math.round(-vector.y * halfHeight + halfHeight)
        };
    }

你可能感兴趣的:(ThreeJS)