Lohmann Lohmann - 6 months ago 132
Javascript Question

Move an object in a threejs scene with mouse

I need to move an object in a threejs scene, but i can't select one object when i click with mouse. I tried adapt this code
(https://github.com/mrdoob/three.js/blob/master/examples/webgl_interactive_draggablecubes.html) for my application, but it didn't work in my case.

This function was correct?

The camera position and rotate is correct (see complete code)?

function onDocumentMouseDown(event) {
console.log("function onDocumentMouseDown");
console.log(mouse.x, mouse.y);
raycaster.setFromCamera( mouse, camera );
var intersects = raycaster.intersectObjects( objetos );

if (intersects.length > 0) {
alert("finalmente");
console.log(intersects[0]);
intersects[0].object.material.transparent = true;
intersects[0].object.material.opacity = 0.1;
SELECTED = intersects[0].object;
var intersects = raycaster.intersectObject( plane );
if ( intersects.length > 0 ) {
offset.copy( intersects[ 0 ].point ).sub(plane.position);
}
}
}


For complete code access https://github.com/lohmanndouglas/Simulador.git

Answer

The problem was caused because I am using others DIV in my page, so to correct this problem its necessary to convert clientX and clientY to the relative coordinate of the DIV.

I changed the lines where I update the variables mouse.x and mouse.y.

    mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
    mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;

For this:

   mouse.x = ( (event.clientX - event.target.getBoundingClientRect().left) /event.currentTarget.width ) * 2 - 1;
   mouse.y = - ( (event.clientY - event.target.getBoundingClientRect().top) / event.currentTarget.height ) * 2 + 1;

This works for me

Comments