Detect clicked object in THREE.js

后端 未结 4 2218
爱一瞬间的悲伤
爱一瞬间的悲伤 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 01:58

    I ran into problems trying to implement this for a canvas which does not take up the entire width and height of the screen. Here is the solution I found works quite well.

    Initialize everything on an existing canvas:

    var init = function() {
      var canvas_model = document.getElementById('model')
      var viewSize = 50 // Depending on object size, canvas size etc.
      var camera = new THREE.OrthographicCamera(-canvas_model.clientWidth/viewSize, canvas_model.clientWidth/viewSize, canvas_model.clientHeight/viewSize, -canvas_model.clientHeight/viewSize, 0.01, 2000),
    }
    

    Add an event listener to the canvas:

    canvas_model.addEventListener('click', function(event){
      var bounds = canvas_model.getBoundingClientRect()
      mouse.x = ( (event.clientX - bounds.left) / canvas_model.clientWidth ) * 2 - 1;
      mouse.y = - ( (event.clientY - bounds.top) / canvas_model.clientHeight ) * 2 + 1;
      raycaster.setFromCamera( mouse, camera );
      var intersects = raycaster.intersectObjects(scene.children, true);
      if (intersects.length > 0) {
         // Do stuff
      }
    }, false)
    

    Or for a 'touchstart' event, change the lines calculating the mouse.x and mouse.y into:

    mouse.x = ( (event.touches[0].clientX - bounds.left) / canvas_model.clientWidth ) * 2 - 1;
    mouse.y = - ( (event.touches[0].clientY - bounds.top) / canvas_model.clientHeight ) * 2 + 1;
    

提交回复
热议问题