Three.js |是否可以使用raycaster将光线从一个物体投射到另一个物体?

时间:2017-11-14 12:51:02

标签: three.js

我需要将光线从物体投射到场景中的另一个物体。

是否可以在Three.js中进行操作,因为我在初始搜索中找不到任何内容。

即使将它从对象转换为原点(0,0,0)也适用于我。

提前致谢。

我这样做是为了将光线从物体投射到原点。

var origin = new THREE.Vector3( 0,0,0 );
var pos = mesh.position.clone().sub( origin );

pos.normalize();
raycaster.set( mesh.position , pos.normalize() );

var intersects = raycaster.intersectObjects( scene.children );

for ( var i = 0; i < intersects.length; i ++ ) {

    intersects[i].object.material.color.setHex( 0xffffff );

}

1 个答案:

答案 0 :(得分:1)

这是一个例子。雷卡斯特的射线从红色球体变为蓝色球体。它们之间的所有物体随机改变颜色,而光线与它们相交。

&#13;
&#13;
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.set(0, 10, 15);
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

var controls = new THREE.OrbitControls(camera, renderer.domElement);

scene.add(new THREE.AmbientLight(0xffffff, .5));
var light = new THREE.DirectionalLight(0xffffff, .5);
light.position.set(10, 10, -10);
scene.add(light);

scene.add(new THREE.GridHelper(20, 20, "gray", "gray"));

var objects = [];
for (let i = 0; i < 20; i++) {
  let obj = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), new THREE.MeshLambertMaterial({
    color: Math.random() * 0xffffff
  }));
  obj.position.set(
    THREE.Math.randInt(-10, 10),
    .5,
    THREE.Math.randInt(-10, 10)
  );
  objects.push(obj);
  scene.add(obj);
}

var objOrigin = new THREE.Mesh(new THREE.SphereGeometry(.5, 16, 12), new THREE.MeshLambertMaterial({
  color: "red"
}));
scene.add(objOrigin);
var objDestin = new THREE.Mesh(new THREE.SphereGeometry(.5, 16, 12), new THREE.MeshLambertMaterial({
  color: "blue"
}));
scene.add(objDestin);


var raycaster = new THREE.Raycaster();
var intersects;
var direction = new THREE.Vector3();
var far = new THREE.Vector3();
var clock = new THREE.Clock();
var time = 0;

render();

function render() {
  time += clock.getDelta();
  requestAnimationFrame(render);
  objOrigin.position.set(
    Math.cos(time) * ( 7 + Math.sin(time * 10)) ,
    .5,
    Math.sin(time) * ( 7 + Math.sin(time * 10))
  );
  objDestin.position.set(
    Math.cos(time + Math.PI) * 7,
    .5,
    Math.sin(time + Math.PI) * 7
  );
  raycaster.set(objOrigin.position, direction.subVectors(objDestin.position, objOrigin.position).normalize());
  raycaster.far = far.subVectors(objDestin.position, objOrigin.position).length(); // comment this line to have an infinite ray
  intersects = raycaster.intersectObjects(objects);
  for (let i = 0; i < intersects.length; i++) {
    intersects[i].object.material.color.set(Math.random() * 0xffffff);
  }
  renderer.render(scene, camera);
}
&#13;
body {
  overflow: hidden;
  margin: 0;
}
&#13;
<script src="https://threejs.org/build/three.min.js"></script>
<script src="https://threejs.org/examples/js/controls/OrbitControls.js"></script>
&#13;
&#13;
&#13;