我是three.js的新手,我使用http://threejs.org/examples/webgl_interactive_draggablecubes.html的例子来拖放我的对象。问题是我希望它们只能在XZ平面上移动(而不是在Y轴上),我不知道如何实现它以便在平面上移动它们。用户应该只能在地面上“滑动”它们。我正在使用OrbitControls而不是TrackballControls。
https://jsfiddle.net/d58bbLey/
function onDocumentMouseMove( event ) {
event.preventDefault();
mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;
raycaster.setFromCamera( mouse, camera );
if ( SELECTED ) {
var intersects = raycaster.intersectObject( plane );
if ( intersects.length > 0 ) {
SELECTED.position.copy( intersects[ 0 ].point.sub( offset ) );
}
return;
}
var intersects = raycaster.intersectObjects( objects );
if ( intersects.length > 0 ) {
if ( INTERSECTED != intersects[ 0 ].object ) {
if ( INTERSECTED ) INTERSECTED.material.color.setHex( INTERSECTED.currentHex );
INTERSECTED = intersects[ 0 ].object;
INTERSECTED.currentHex = INTERSECTED.material.color.getHex();
plane.position.copy( INTERSECTED.position );
plane.lookAt( camera.position );
}
container.style.cursor = 'pointer';
} else {
if ( INTERSECTED ) INTERSECTED.material.color.setHex( INTERSECTED.currentHex );
INTERSECTED = null;
container.style.cursor = 'auto';
}
}
感谢您的帮助! :d
答案 0 :(得分:0)
最后我发现了问题: 每个物体都有一个看起来像相机的平面。所以,我删除了plane.lookAt(camera.position)并添加了这一行:
plane.applyMatrix(new THREE.Matrix4().makeRotationX( -Math.PI / 2));
现在我的物体停留在飞机上(XZ轴)。
答案 1 :(得分:0)
我必须做同样的事情,到目前为止,我使用了DragControls
const geometry = new THREE.SphereGeometry(5, 32, 32);
const materialSphere = new THREE.MeshBasicMaterial({ color: 0xff0000, side: THREE.DoubleSide, wireframe: true });
const sphereMesh = new THREE.Mesh(geometry, materialSphere);
this.scene.add(sphereMesh);
this.dragControls = new DragControls([sphereMesh], camera, renderer.domElement);
this.dragControls.addEventListener('drag', (event) => {
event.object.position.z = 0;
event.object.position.x = 0;
});