如何投射可见射线三js

时间:2015-07-27 14:29:10

标签: three.js

我想瞄准具有相机视觉的物体(因为用户会看到物体,而不是用鼠标指向它)。

我正在像这样从相机投射光线

rotation.x = camera.rotation.x;
    rotation.y = camera.rotation.y;
    rotation.z = camera.rotation.z;
    raycaster.ray.direction.copy( direction ).applyEuler(rotation);
    raycaster.ray.origin.copy( camera.position );

var intersections = raycaster.intersectObjects( cubes.children );

这让我得到了交叉点,但它似乎有时会徘徊。所以我想添加目标(十字准线)。那将是光线末端或中间的物体(网格)上的某种东西。

我该如何添加?当我创建一个常规线时,它位于相机前面,因此屏幕会变黑。

1 个答案:

答案 0 :(得分:7)

您可以将简单几何体构造的十字准线添加到相机中,如下所示:

var material = new THREE.LineBasicMaterial({ color: 0xAAFFAA });

// crosshair size
var x = 0.01, y = 0.01;

var geometry = new THREE.Geometry();

// crosshair
geometry.vertices.push(new THREE.Vector3(0, y, 0));
geometry.vertices.push(new THREE.Vector3(0, -y, 0));
geometry.vertices.push(new THREE.Vector3(0, 0, 0));
geometry.vertices.push(new THREE.Vector3(x, 0, 0));    
geometry.vertices.push(new THREE.Vector3(-x, 0, 0));

var crosshair = new THREE.Line( geometry, material );

// place it in the center
var crosshairPercentX = 50;
var crosshairPercentY = 50;
var crosshairPositionX = (crosshairPercentX / 100) * 2 - 1;
var crosshairPositionY = (crosshairPercentY / 100) * 2 - 1;

crosshair.position.x = crosshairPositionX * camera.aspect;
crosshair.position.y = crosshairPositionY;

crosshair.position.z = -0.3;

camera.add( crosshair );
scene.add( camera );

Three.js r.71

http://jsfiddle.net/L0rdzbej/9/

如果您没有特殊的用例,您需要从相机中检索位置和旋转,就像您正在做的那样,我想您的徘徊"可以通过用这些参数调用你的raycaster来修复。:

raycaster.set( camera.getWorldPosition(), camera.getWorldDirection() );
var intersections = raycaster.intersectObjects( cubes.children );

投射可见光线 然后,您可以通过使用箭头帮助器绘制箭头来在3D空间中可视化您的光线投射。在光线投射后执行此操作:

scene.remove ( arrow );
arrow = new THREE.ArrowHelper( camera.getWorldDirection(), camera.getWorldPosition(), 100, Math.random() * 0xffffff );
scene.add( arrow );