Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the mouse position using three.js?

Hi I'm using IcosahedronGeometry. In that I'm adding CircleGeometry to each of its vertices. So now my requirement is when the mouse is moved towards the circle, the circle should sense the mousemove and it should move towards the mouse. So for that i have created a RingGeometry around the circle. So if the mouse move towards the ring, circle should sense the position of the mouse.

But I'm unable to get the mouse position. I'm using raycaster, is there any other alternative to find the position of the mouse?

like image 950
disciple Avatar asked Jun 16 '15 06:06

disciple


3 Answers

Raycaster is standard way for this:

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

var objects = raycaster.intersectObjects(scene.children);

http://jsfiddle.net/nhvff8ra/6/

like image 70
stdob-- Avatar answered Sep 28 '22 18:09

stdob--


I did the following (some parts are omitted for brevity):

// Use of the Raycaster inspired by  webgl_interactive_cubes.html, in the THREE.js project examples directory
raycaster = new THREE.Raycaster();
mouse = new THREE.Vector2()
document.addEventListener('mousemove', onDocumentMouseMove, false);
window.addEventListener('resize', onWindowResize, false);
document.addEventListener('mousedown', onMouseDown, false);


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

function onWindowResize() {
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();
    renderer.setSize(window.innerWidth, window.innerHeight);
}

function manageRaycasterIntersections(scene, camera) {
    camera.updateMatrixWorld();
    raycaster.setFromCamera(mouse, camera);
    var intersects = raycaster.intersectObjects(scene.children);

    if (intersects.length > 0) {

    } 
    else {

    }
}

function onMouseDown(event){
   customLog("mouse position: (" + mouse.x + ", "+ mouse.y + ")");
}

Take a look at this for the complete code

like image 34
Evil Toad Avatar answered Sep 28 '22 19:09

Evil Toad


Are you looking for something like this?

var cursorX;
var cursorY;
document.onmousemove = function(e){
    cursorX = e.pageX;
    cursorY = e.pageY;
}
setInterval("checkCursor()", 1000);
function checkCursor(){
    alert("Cursor at: " + cursorX + ", " + cursorY);
}
like image 37
Collin Avatar answered Sep 28 '22 19:09

Collin