I'm currently working on positioning an object called 'tracer' under my mouse cursor. You can view my jsfiddle here.
While researching, I came across this question, but I had difficulty applying it to my project.
In my scene, I have a basic setup with just a cube and a light. My goal is to have a pointer move beneath the mouse whenever it moves.
I've managed to achieve this using raycasting and intersecting objects. However, I also want the tracer to always follow the mouse, even when not intersecting with any objects. Here's the code for the object I want to position 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 );
This is how I retrieve the mouse position and set the tracer's position:
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 ) );
tracer.position.copy( pos );
}
Despite my efforts, the tracer doesn't perfectly align underneath the mouse, instead moving slightly. Any assistance would be greatly appreciated.