Detect clicked object in THREE.js

后端 未结 4 2238
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-01 01:20

I have a THREE.js scene where a lot of elements appear, and I need to detect what object the user is clicking on.

What I have done so far is the following. The camer

4条回答
  •  时光说笑
    2020-12-01 02:12

    Depends on what kind of camera are you using.

    1) PerspectiveCamera: is ok link that Mr.doob provides.
    2) OrthographicCamera: is quite different:

    var init = function() {
      camera = new THREE.OrthographicCamera( SCREEN_WIDTH / - 2, SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2, SCREEN_HEIGHT / - 2, NEAR, FAR);
      document.addEventListener( 'mousedown', onDocumentMouseDown, false );
    }
    
    function onDocumentMouseDown( e ) {
      e.preventDefault();
      var mouseVector = new THREE.Vector3();
      mouseVector.x = 2 * (e.clientX / SCREEN_WIDTH) - 1;
      mouseVector.y = 1 - 2 * ( e.clientY / SCREEN_HEIGHT );
      var raycaster = projector.pickingRay( mouseVector.clone(), camera );
      var intersects = raycaster.intersectObject( TARGET );
      for( var i = 0; i < intersects.length; i++ ) {
        var intersection = intersects[ i ],
        obj = intersection.object;
        console.log("Intersected object", obj);
      }
    }
    

提交回复
热议问题