2016-08-29 38 views
3

我試圖檢測我的平面網格上的點擊。我使用這些示例作爲指導,設置了一個raycaster。Three.js不準確的Raycaster

下面是代碼: http://jsfiddle.net/BAR24/o24eexo4/2/

當單擊該標記線之下,沒有點擊會即使點擊是在飛機上(標記線沒有作用)檢測。

也嘗試調整屏幕大小。然後,即使點擊標記線上方也不行。

也許這與使用正交相機有關嗎?或者不更新一些需要的矩陣?

function onMouseDown(event) { 
    event.preventDefault(); 

    mouse.x = (event.clientX/window.innerWidth) * 2 - 1; 
    mouse.y = -(event.clientY/window.innerHeight) * 2 + 1; 
    //console.log("x: " + mouse.x + ", y: " + mouse.y); 

    raycaster.setFromCamera(mouse, camera) 

    var intersects = raycaster.intersectObjects(objects); 

    if (intersects.length > 0) { 
    console.log("touched:" + intersects[0]); 
    } else { 
    console.log("not touched"); 
    } 
} 

回答

4

您的CSS會影響您的光線投射計算。你可以做的一件事是設置

body { 
    margin: 0px; 
} 

欲瞭解更多信息,請參閱THREE.js Ray Intersect fails by adding div

您還必須正確處理窗口大小調整。典型模式如下所示:

function onWindowResize() { 

    var aspect = window.innerWidth/window.innerHeight; 

    camera.left = - frustumSize * aspect/2; 
    camera.right = frustumSize * aspect/2; 
    camera.top = frustumSize/2; 
    camera.bottom = - frustumSize/2; 

    camera.updateProjectionMatrix(); 

    renderer.setSize(window.innerWidth, window.innerHeight); 

} 

研究three.js示例。具體見http://threejs.org/examples/webgl_interactive_cubes_ortho.html

另外,請閱讀this answer,其中描述瞭如何正確實例化正交相機。

three.js所R.80

+0

看起來像修復了小提琴的例子。將在明天測試我的程序。謝謝! – BAR

0

嘗試......它會在任何地方工作,即使你有保證金和滾動!

function onMouseDown(event) { 
     event.preventDefault(); 

     var position = $(WGL.ctx.domElement).offset(); // i'm using jquery to get position 
     var scrollUp = $(document).scrollTop(); 
     if (event.clientX != undefined) { 
      mouse.x = ((event.clientX - position.left)/WGL.ctx.domElement.clientWidth) * 2 - 1; 
      mouse.y = - ((event.clientY - position.top + scrollUp)/WGL.ctx.domElement.clientHeight) * 2 + 1; 
     } else { 
      mouse.x = ((event.originalEvent.touches[0].pageX - position.left)/WGL.ctx.domElement.clientWidth) * 2 - 1; 
      mouse.y = - ((event.originalEvent.touches[0].pageY + position.top - scrollUp)/WGL.ctx.domElement.clientHeight) * 2 + 1; 
     } 

     raycaster.setFromCamera(mouse, camera) 
     var intersects = raycaster.intersectObjects(objects); 
    } 
相關問題