Shawn
Shawn

Reputation: 88

In Three.js, How do I get the right coordinates when the user drags their mouse

I am using ThreeJS. I need to draw a rectangle as the user clicks and drags their mouse.

I am using threejs.

    function onDrag(event) {
        if (!isDrawing) { return; }
        // The rectangle should follow the users mouse 
        var clientX = (event.pageX - startPosition.x) / 50;
        var clientY = (event.pageY - startPosition.y) / 50;
        var vertices = geometry.vertices;
        vertices[1].x = -clientX * -1;
        vertices[2].x = -clientX * -1;
        vertices[2].z = -clientY * -1;
        vertices[3].z = -clientY * -1;
        geometry.verticesNeedUpdate = true;
    }

// For the full code please follow this link https://jsfiddle.net/shawnswebsites/tcpakwgL/1/

The rectangle should follow the users mouse after the mouse down event. But the rectangle does not follow the mouse, it is considerable smaller than what the user is drawing. Can anyone tell me what I am doing wrong

Upvotes: 0

Views: 101

Answers (1)

Mugen87
Mugen87

Reputation: 31086

It seems you are mixing different space in your fiddle. So it's not correct to directly assign window coordinates to vertex data. Instead, try to work always in world space which can easily done by using the result of your current raycasting logic. Try it like so:

function onDrag( event ) {

    if ( ! isDrawing ) return;

    var current = get3DPosition( event );

    var x = current.x;
    var z = current.z;

    geometry.vertices[ 1 ].x = x;
    geometry.vertices[ 2 ].x = x;
    geometry.vertices[ 2 ].z = z;
    geometry.vertices[ 3 ].z = z;
    geometry.verticesNeedUpdate = true;

}

Demo: https://jsfiddle.net/qw03d14o/1/

It was also necessary to refactor some of your code since the plane should ideally placed on top of the ground without a y-offset. I've set polygonOffset and polygonOffsetFactor for the respective material in order to avoid z-fighting.

Upvotes: 1

Related Questions