Stefano Maglione
Stefano Maglione

Reputation: 4150

Three.js draggable shape

I'm studing this code for draggable cube

but I can't understand the reason of create an offset between plane and selected object like in this part of code:

function onDocumentMouseDown( event ) {

            event.preventDefault();

            var vector = new THREE.Vector3( mouse.x, mouse.y, 0.5 );
            projector.unprojectVector( vector, camera );

            var raycaster = new THREE.Raycaster( camera.position, vector.sub( camera.position ).normalize() );

            var intersects = raycaster.intersectObjects( objects );

            if ( intersects.length > 0 ) {

                controls.enabled = false;

                SELECTED = intersects[ 0 ].object;

                var intersects = raycaster.intersectObject( plane );
                offset.copy( intersects[ 0 ].point ).sub( plane.position );// OFFSET

                container.style.cursor = 'move';

            }

        }

Upvotes: 0

Views: 2343

Answers (1)

gevaraweb
gevaraweb

Reputation: 923

Object coordinates when moving are counted concerning coordinates of hit of a mouse on the plane therefore there is a shift. It is possible to do without offset:

function onDocumentMouseMove( event ) {

    ...if ( SELECTED ) {

       var intersects = raycaster.intersectObject( plane );
       SELECTED.position.copy( intersects[ 0 ].point );

   }
}

Try, and you will feel a difference. Also you can make on the basis of an this example. Look at messages in the console.

<script src="js/controls/EventsControls.js"></script>

EventsControls = new EventsControls( camera, renderer.domElement );

EventsControls1.attachEvent( 'dragAndDrop', function () {

    this.container.style.cursor = 'move';
    this.focused.position.y = this.previous.y;

});

var mesh = new THREE.Mesh( geometry, material );
scene.add( mesh ); 

EventsControls.attach( mesh );

Upvotes: 1

Related Questions