简体   繁体   English

除非我单击并轻轻拖动,否则使用Three.js的mousedown事件将不起作用

[英]The mousedown event using Three.js doesn't work unless I click and slightly drag

For some reason, in the code below, the "intersects" variable does not contain any items in the onDocumentMouseDown event handler when I simply click an object. 由于某些原因,在下面的代码中,当我单击对象时,“ intersects”变量在onDocumentMouseDown事件处理程序中不包含任何项目。 In order for it to detect the object clicked, I have to click and slightly drag the mouse before it picks up the item clicked. 为了使其能够检测到单击的对象,我必须单击并稍微拖动鼠标,然后鼠标才能拾取单击的项目。 I am also using trackballcontrols if that matters. 如果这很重要,我也正在使用trackballcontrols。 I have a jsfiddle example here: http://jsfiddle.net/marktreece/xvQ3f/ 我在这里有一个jsfiddle示例: http : //jsfiddle.net/marktreece/xvQ3f/

In the jsfiddle example, click on the cube and notice that the color does not change as expected. 在jsfiddle示例中,单击多维数据集,然后注意到颜色没有按预期变化。 Now click the cube and before releasing the mouse button, move it slightly and the color changes. 现在单击该多维数据集,然后释放鼠标按钮,将其稍微移动,颜色就会改变。 How can I make it so that simply clicking the object will be enough? 我怎样才能做到,只需单击对象就足够了?

Here is my mousedown event handler: 这是我的mousedown事件处理程序:

function onDocumentMouseDown( event ) {
    event.preventDefault();
    var vector = new THREE.Vector3( ( event.clientX / window.innerWidth ) * 2 - 1, - ( event.clientY / window.innerHeight ) * 2 + 1, 0.5 );
    projector.unprojectVector( vector, camera );
    var raycaster = new THREE.Raycaster( camera.position, vector.sub( camera.position ).normalize() );
    var intersects = raycaster.intersectObjects( scene.children, true );
    if ( intersects.length > 0 ) {
        intersects[ 0 ].object.material.color.setHex( Math.random() * 0xffffff );
    }
}

From what I can see, in your example raycasting works fine and intersects variable is not empty. 从我可以看到的角度来看,在您的示例中,光线投射效果很好,并且相交变量不为空。 The problem is that as you are using TrackballControls, the rendering is performed only when the camera changes its position. 问题在于,当您使用TrackballControls时,仅在相机更改其位置时才执行渲染。 That is why a small drag of the mouse results in changing the color of the box. 这就是为什么只需拖动鼠标即可更改框的颜色的原因。

Below I included your animate function with one new call to render function. 下面,我将动画函数与一个新调用的render函数一起包括在内。 This solves the problem. 这样就解决了问题。 However, note that this is not the most efficient solution as the rendering is performed every frame. 但是,请注意,这不是最有效的解决方案,因为渲染是每帧执行一次。

function animate() {
    try{
        requestAnimationFrame( animate );
        controls.update();
        render();
    }
    catch(err){
        alert("animate error. " + err.message);
    }
}

Hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM