2

I'm new to three.js and I used the example of http://threejs.org/examples/webgl_interactive_draggablecubes.html to drag and drop my objects. The problem is that I want them to move only on the XZ plane (not on the Y axis) and I don't know how to achieve it in order to move them on a plane. The user should only be able to "slide" them on the ground. I'm using the OrbitControls instead of the 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';
    }
}

I appreciate your help! :D

2 Answers 2

0

Finally I found the problem: each object has a plane which lookAt the camera. So, I deleted the plane.lookAt(camera.position) and added this line:

plane.applyMatrix(new THREE.Matrix4().makeRotationX( -Math.PI / 2));

Now my objects stays on the plane (XZ axis).

2
0

I have to do the same stuff, so far I used the 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;
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.