如何从任意点进行Raycast

时间:2016-04-15 06:50:56

标签: javascript three.js

所以这是我的问题,因为我在项目中使用三个j,用户给出x y坐标,在三个js场景上添加一个点,我需要计算碰撞对象在后面/前面的位置这一点。我尝试使用Raycaster,但我找不到一个简单的示例,说明如何将Raycaster与由point定义的向量一起使用:/ 到目前为止这是我的代码

var projector = new THREE.Projector();
    var directionVector = new THREE.Vector3();
     /* how could i use a vector defined by my origin point

     var origin = new THREE.Vector3(x, y, 0 );

     instead of the camera vector as used below ? 
     */
     projector.unprojectVector(directionVector, camera);
     directionVector.sub(camera.position);
     directionVector.normalize();
     var ray = new THREE.Raycaster();
     ray.set(camera.position,directionVector)
     var intersects = ray.intersectObjects(scene.children);
        if (intersects.length > 0) {
            console.log(intersects);
        }

1 个答案:

答案 0 :(得分:1)

要从任意点进行光线投射,您可以使用此模式:

var raycaster = new THREE.Raycaster(); // create once, and reuse
var origin = new THREE.Vector3(); // reuse it
var direction = new THREE.Vector3(); // reuse it
...

origin.set( x, y, z );
direction.set( 0, 0, - 1 ).normalize(); // direction vector must have unit length
raycaster.set( origin, direction );
var intersects = raycaster.intersectObjects( objects, recursiveFlag );
if ( intersects.length > 0 ) {      
    // your code        
}

three.js r.75