我在three.js中创建了一个框
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera( 100, window.innerWidth/window.innerHeight, 0.1, 1000 );
camera.position.set(5, 5, 10);
var geo = new THREE.BoxGeometry(5,2,5);
var mat = new THREE.MeshBasicMaterial({color:0xff0ff0, wireframe:false, vertexColors: THREE.FaceColors});
var mesh = new THREE.Mesh( geo, mat);
scene.add(mesh);
var renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
renderer.render(scene, camera);
之后我想光线投射到鼠标悬停在其上的立方体面孔。因此我创建了这个功能
var raycaster = new THREE.Raycaster();
var mouse = new THREE.Vector2();
function onMouseMove( event ) {
mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;
raycaster.setFromCamera( mouse, camera );
var intersects = raycaster.intersectObject( mesh);
for ( var i = 0; i < intersects.length; i++ ) {
intersects[ i ].face.color.setHex( 0xDDC2A3);
mesh.geometry.colorsNeedUpdate = true;
}
renderer.render( scene, camera );
}
window.addEventListener( 'mousemove', onMouseMove, false );
几乎工作正常。我的意思是,它会改变脸部一半的颜色。你知道,由BoxGeometry()
创建的网格有12 Face3
。我想要{strong>完整的面孔或硬面或 Face4
,这些都是Face3+Face3
形成的。知道我怎么能做到这一点吗?
答案 0 :(得分:0)
在您的具体示例中,假设您使用默认的盒子几何体并且我们知道每侧有2个面,包裹在特定的方向/顺序中,您应该能够将两个面中的每一个配对在一起像这样:
var facesPerSide = 2;
for ( var i = 0; i < intersects.length; i++ ) {
var side = Math.floor(intersects[i].faceIndex/facesPerSide);
for(var j=0;j<facesPerSide;j++) {
mesh.geometry.faces[side*facesPerSide+j].color.setHex(0xDDC2A3);
}
mesh.geometry.colorsNeedUpdate = true;
}
编辑:显然,如果对宽度/高度/深度使用可变数量的段,或者如果使用非柏拉图实体几何,则会更复杂。
答案 1 :(得分:0)
仅适用于现成的非缓冲几何,如BoxGeometry,SphereGeometry,CircleGeometry等......
var intersects = raycaster.intersectObject( mesh);
for ( var i = 0; i < intersects.length; i++ ) {
var faceIndex = intersects[i].faceIndex;
if(faceIndex == 0 || (faceIndex % 2) == 0) {
intersects[i].object.geometry.faces[faceIndex].color.setHex( 0xD1B3B3);
intersects[i].object.geometry.faces[faceIndex + 1].color.setHex( 0xD1B3B3);
intersects[i].object.geometry.colorsNeedUpdate = true;
}else {
intersects[i].object.geometry.faces[faceIndex].color.setHex( 0xD1B3B3);
intersects[i].object.geometry.faces[faceIndex - 1].color.setHex( 0xD1B3B3);
intersects[i].object.geometry.colorsNeedUpdate = true;
}
}
renderer.render(scene, camera);