Joy
Joy

Reputation: 9550

Three.js: not accurate to detect faceIndex when clicking the 2*2*2 geometry cube

I have created a 2*2*2 geometry cube via Three.js. Now I want to detect the click event when clicking the faces (24 faces in total).

Please check my current implementation at https://jsfiddle.net/agongdai/pdwg3myr/17/. When clicking on the faces, I want to console.log the current face index. But the index is not always accurate. For example, clicking on the top-left gray cell should show 0, but actually clicking the bottom part of it shows 2.

Please help me to check the mouse click event handler:

var raycaster = new THREE.Raycaster();
function onDocumentMouseDown( event ) {

   var vector = new THREE.Vector3( 
      ( event.clientX / window.innerWidth ) * 2 - 1, 
      - ( event.clientY / window.innerHeight ) * 2 + 1, 0.5 );
   vector.unproject( camera );
   raycaster.setFromCamera( vector, camera );
   raycaster.set( camera.position, vector.sub( camera.position ).normalize() );

   var intersects = raycaster.intersectObject( cube );
   if ( intersects.length > 0 ) {
      var index = Math.floor( intersects[0].faceIndex / 2 );
      console.log(index);
   }
}

Could anybody please help?

Upvotes: 1

Views: 617

Answers (1)

Joy
Joy

Reputation: 9550

Em, after googling a lot, I found this page and applied the approach. It's working properly https://jsfiddle.net/agongdai/pdwg3myr/19/:

var raycaster = new THREE.Raycaster();
var mouse = new THREE.Vector2();
function onDocumentMouseDown(event) {
  mouse.x = (event.clientX / renderer.domElement.clientWidth) * 2 - 1;
  mouse.y = -(event.clientY / renderer.domElement.clientHeight) * 2 + 1;
  raycaster.setFromCamera(mouse, camera);
  var intersects = raycaster.intersectObject(cube);
  if (intersects.length > 0) {
    var index = Math.floor(intersects[0].faceIndex / 2);
    console.log(index);
  }
}

Update

To adjust to the left/top shift and scrolling, update it to https://jsfiddle.net/agongdai/pdwg3myr/24/:

function onDocumentMouseDown(event) {
  const holder = renderer.domElement;
  const rect = holder.getBoundingClientRect();
  mouse.x = ((event.pageX - rect.left - window.scrollX) / holder.clientWidth) * 2 - 1;
  mouse.y = -((event.pageY - rect.top - window.scrollY) / holder.clientHeight) * 2 + 1;
  ...
}

Upvotes: 7

Related Questions