0

I'm trying to position an object (called 'tracer') beneath my mouse cursor. My jsfiddle is here.

I found this question but was unable to apply it to my project.

I have a very simple scene with just a cube and a light. Each time the mouse moves, i want to position an pointer underneath it.

I'm able to do it using raycasting and intersecting objects. But I also want to always move the tracer underneath the mouse, even if not intersecting with any objects. Here is the object i want to move under the mouse:

var geometry = new THREE.CylinderGeometry( 0, 20, 100, 3 );
    geometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, 50, 0 ) );
    geometry.applyMatrix( new THREE.Matrix4().makeRotationX( Math.PI / 2 ) );
var tracer = new THREE.Mesh( geometry, new THREE.MeshNormalMaterial() );
scene.add( tracer );

And this is what i do to get the position of the mouse and then set the position of the tracer:

function onMouseMove( event ) {

    mouse.x = ( event.clientX / renderer.domElement.width ) * 2 - 1;
    mouse.y = - ( event.clientY / renderer.domElement.height ) * 2 + 1;

    vector.set(
      ( event.clientX / window.innerWidth ) * 2 - 1,
      - ( event.clientY / window.innerHeight ) * 2 + 1,
     .5 );

    var dir = vector.sub( camera.position ).normalize();

    var distance = - camera.position.z / dir.z;

    var pos = camera.position.clone().add( dir.multiplyScalar( distance     ) );
    console.log('pos is ');
    console.log(pos);

    tracer.position.copy( pos );
}

However, the tracer does not move underneath the mouse, though it moves slightly. Any help greatly appreciated.

Community
  • 1
  • 1
Mark
  • 4,428
  • 14
  • 60
  • 116

1 Answers1

1

Here is a version that keeps an object under the mouse and in the plane z = 0 -- and does not clone a new THREE.Vector3() every call:

var mouse = new THREE.Vector2();
var vector = new THREE.Vector3();

function onMouseMove(event) {

    mouse.x = ( event.clientX / renderer.domElement.width ) * 2 - 1;

    mouse.y = - ( event.clientY / renderer.domElement.height ) * 2 + 1;

    vector.set( ( event.clientX / window.innerWidth ) * 2 - 1, - ( event.clientY / window.innerHeight ) * 2 + 1, 0.5 );

    vector.unproject( camera );

    var dir = vector.sub( camera.position ).normalize();

    var distance = - camera.position.z / dir.z;

    tracer.position.copy( camera.position ).add( dir.multiplyScalar( distance ) );

}

fiddle: http://jsfiddle.net/ybndL7ro/6/

three.js r.70

WestLangley
  • 102,557
  • 10
  • 276
  • 276