raycaster.intersectObjects不起作用:使用three.js提供空数组

时间:2015-04-17 01:20:31

标签: javascript 3d three.js

看起来“raycaster.intersectObjects”没有反应(使用Three.js r54)。从代码中提取(包括重要部分)如下:

var renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
var camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 1000 );
camera.position.z = 75;
scene = new THREE.Scene();
document.addEventListener( 'mousedown', onDocumentMouseDown, false );

var raycaster = new THREE.Raycaster();
var mouseVector = new THREE.Vector2();

function onDocumentMouseDown( e ) {
    e.preventDefault();
    mouseVector.x = ( e.clientX / window.innerWidth ) * 2 - 1;
    mouseVector.y = - ( e.clientY / window.innerHeight ) * 2 + 1;
    var intersects = raycaster.intersectObjects(scene.children, true);
    console.log(intersects);
    if (intersects.length>0){
        intersects[ 0 ].object.material.color.setHex( Math.random() * 0xffffff );
    }
}

function render() {  
    requestAnimationFrame(render);           
    mesh.rotation.y += 0.005;
    renderer.render(scene, camera);
}

我在代码“console.log”里面调试问题,发现它在控制台中输出空数组。之间,我得到空数组的输出,不依赖于我是单击某个对象还是仅单击背景。

1 个答案:

答案 0 :(得分:5)

根据http://threejs.org/docs/#Reference/Core/Raycaster,你忘了这句话:

// update the picking ray with the camera and mouse position    
raycaster.setFromCamera( mouseVector, camera ); 

在致电raycaster.intersectObjects()

之前

three.js r71

修改

在three.js r54中 onDocumentMouseDown()函数应该如下所示:

function onDocumentMouseDown( e ) {
    e.preventDefault();

    var mouseVector = new THREE.Vector3(
        ( e.clientX / window.innerWidth ) * 2 - 1,
      - ( e.clientY / window.innerHeight ) * 2 + 1,
        1 );

    projector.unprojectVector( mouseVector, camera );
    var raycaster = new THREE.Raycaster( camera.position, mouseVector.subSelf( camera.position ).normalize() );

    // create an array containing all objects in the scene with which the ray intersects
    var intersects = raycaster.intersectObjects( scene.children );
    console.log(intersects);
    if (intersects.length>0){
        console.log("Intersected object:", intersects.length);
        intersects[ 0 ].object.material.color.setHex( Math.random() * 0xffffff );
    }
}

并在init()中添加:

// initialize object to perform world/screen calculations
projector = new THREE.Projector();

这是一个小提琴:http://jsfiddle.net/5z13yzgx/