用鼠标选择对象 - Three.js

Selecting object with mouse - Three.js

我知道这个问题已经被问过了。如果用鼠标选中,我希望能够更改对象的颜色。我尝试自己编写代码,但它似乎不起作用,所以我想我遗漏了一些东西。这基本上就是脚本:

    <script>
        var scene = new THREE.Scene();
        var camera = new THREE.PerspectiveCamera( 75, window.innerWidth/window.innerHeight, 0.1, 1000 );
        var renderer = new THREE.WebGLRenderer();
        renderer.setSize( window.innerWidth/2, window.innerHeight/2 );
        renderer.setClearColor( 0xcccccc, 1 ); 
        document.body.appendChild( renderer.domElement );
        scene.add(camera);

        var geometry = new THREE.Geometry();
        geometry.vertices.push(
            new THREE.Vector3( -5,  5, 0 ),
            new THREE.Vector3( -5, -5, 0 ),
            new THREE.Vector3(  5, -5, 0 )
        );
        var face = new THREE.Face3(0, 1, 2);
        geometry.faces.push(face);
        var material = new THREE.MeshBasicMaterial({color: 0x3300ff});
        var triangle = new THREE.Mesh(geometry, material);
        scene.add(triangle);

        camera.position.z = 10;

        document.addEventListener( 'mousedown', onDocumentMouseDown );

        function onDocumentMouseDown( event ) {    
            event.preventDefault();
            var mouse3D = new THREE.Vector3( ( event.clientX / window.innerWidth ) * 2 - 1,   
                                    -( event.clientY / window.innerHeight ) * 2 + 1,  
                                    0.5 );     
            var projector = new THREE.Projector();                                        
            var raycaster = projector.pickingRay( mouse3D.clone(), camera );
            var intersects = raycaster.intersectObjects( objects );

            if ( intersects.length > 0 ) {
                intersects[ 0 ].object.material.color.setHex( Math.random() * 0xffffff );
            }
        }

        var render = function () {
            requestAnimationFrame( render );
            camera.lookAt( scene.position );
            renderer.render( scene, camera );
        };

        render();
    </script>

如果有人能帮助我,我将不胜感激。

更新了您的代码并使 jsfiddle

在 onDocumentMouseDown 添加

var raycaster =  new THREE.Raycaster();                                        
raycaster.setFromCamera( mouse3D, camera );

而不是

var projector = new THREE.Projector();                                        
var raycaster = projector.pickingRay( mouse3D.clone(), camera );

向对象数组添加了三角形网格并更新了渲染器的大小。 我建议您开始使用控制台并进行一些调试。您自己可以轻松找到这些错误。