在我的three.js场景中,我有一些立方体.我想为用户提供用鼠标选择一个盒子的可能性.
这是重要的代码(我使用Three.js版本69.):
function init() {
[...]
camera = new THREE.PerspectiveCamera(VIEW_ANGLE,ASPECT,NEAR,FAR);
[...]
// in a 'for' iteration, I a many boxes in a 'objects' array :
abox = new THREE.Mesh( geometry, material );
objects.push( abox );
[...]
vector = new THREE.Vector3(0,0,0);
raycaster = new THREE.Raycaster();
animate();
document.addEventListener( 'mousedown', onDocumentMouseDown, false );
}
function onDocumentMouseDown( event ) {
event.preventDefault();
if ( camera instanceof THREE.OrthographicCamera ) {
vector.set( ( event.clientX / window.innerWidth ) * 2 - 1, - ( event.clientY / window.innerHeight ) * 2 + 1, - 1 );
vector.unproject( camera );
dir.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
raycaster.set( vector, dir );
} else if ( camera instanceof THREE.PerspectiveCamera ) {
vector.set( ( event.clientX / window.innerWidth ) * 2 - 1, - ( event.clientY / window.innerHeight ) * 2 + 1, 0.5 );
vector.unproject( camera );
raycaster.set( camera.position, vector.sub( camera.position ).normalize() );
}
var intersects = raycaster.intersectObjects( objects , false);
if ( intersects.length > 0 ) {
var intersect = intersects[ 0 ];
// change color of the face
intersect.object.material.color.setHex( Math.random() * 0xFF0000 );
renderer.render(scene, camera);
}
}
当我点击一个立方体时,所选的点(相交)并不完全(接近但不完全)我点击的位置.有一个转变,一个翻译(我尝试使用正交或相机……同样的问题).
欢迎任何帮助.
谢谢
最佳答案 正如WestLangley向我建议的那样,答案是关于画布的偏移.他在这里写了一个很好的解释
THREE.js Ray Intersect fails by adding div