如何投射可见光线 Threejs

问题描述 投票:0回答:1

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

我像这样从相机投射光线

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 );

这让我找到了交叉点,但有时似乎会迷失方向。所以我想添加瞄准(十字准线)。这将是光线末端或中间的物体(网格)上的某种东西。

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

three.js
1个回答
10
投票

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

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 );

三.js r107

http://jsfiddle.net/5ksydn6u/2/


如果您没有特殊的用例,需要像您一样从相机检索位置和旋转,我想您的“徘徊”可以通过使用这些参数调用您的光线投射器来修复。:

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 );
© www.soinside.com 2019 - 2024. All rights reserved.