使用threejs我可以用光线投射我创建的一些网格
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 500 );
var renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
var raycaster = new THREE.Raycaster();
var mouse = new THREE.Vector2();
//创建三角形几何
var material = new THREE.MeshBasicMaterial( { color : 0x00cc00 } );
var geometry = new THREE.Geometry();
geometry.vertices.push( new THREE.Vector3( -0.5, -0.5, 0 ) );
geometry.vertices.push( new THREE.Vector3( 0.5, -0.5, 0 ) );
geometry.vertices.push( new THREE.Vector3( 0.5, 0.5, 0 ) );
//create a new face using vertices 0, 1, 2
var face = new THREE.Face3( 0, 1, 2 );
//add the face to the geometry's faces array
geometry.faces.push( face );
var object1 = new THREE.Mesh( geometry, material );
scene.add( object1 );
camera.position.z = 10;
//获取鼠标位置
function onDocumentMouseMove( event ) {
event.preventDefault();
mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;
}
// render funciton
function animate() {
raycaster.setFromCamera( mouse, camera );
var intersects = raycaster.intersectObject( object1 );
if ( intersects.length > 0 ) console.log( intersects );
renderer.render( scene, camera );
}
//运行
window.addEventListener( 'mousemove', onDocumentMouseMove, false);
window.addEventListener( 'mousemove', animate, false);
animate();
这行代码对我来说非常有用。但我想要这个三角形的索引而不是所有网格的光线投影。我该怎么办?
我试过了但是它不起作用?为什么?
raycaster.insertObject( object1.geometry.vertices );
答案 0 :(得分:0)
Raycaster.intersectObjects documentation
intersects
应该提供相交的face
以及交叉点的point
。您可以检查从点到面顶点的距离与最小阈值(或者只是最近的顶点到point
)的距离,如果它通过则返回顶点。
var iFace = intersects[0].face;
var iPoint = intersects[0].point;
var ab = iFace.a.distanceTo(iFace.b);
var ac = iFace.a.distanceTo(iFace.c);
var bc = iFace.b.distanceTo(iFace.c);
var lambda = Math.min(ab, ac, bc) - 0.1;
if(iFace.a.distanceTo(iPoint) <= lambda){
return iFace.a;
}
if(iFace.b.distanceTo(iPoint) <= lambda){
return iFace.b;
}
if(iFace.c.distanceTo(iPoint) <= lambda){
return iFace.c;
}