jj kk jj kk - 2 months ago 31
Javascript Question

Raycasting hard-faces of a mesh -- Three.js

i created a box in 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);


After that i want to raycast to cubes faces which mouse over on.Thus i created this function

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


It nearly works correct. i mean, it changes color of the half of the face. You know, the mesh which created by
BoxGeometry()
has 12
Face3
. I want the complete face or hard-face or
Face4
which took shape by
Face3+Face3
. Any idea how i can accomplish this?

Answer

Only works for ready-built, non-Buffer geometries like .. BoxGeometry, SphereGeometry, CircleGeometry etc...

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