如何使用three.js获取鼠标位置?

时间:2015-06-16 06:58:09

标签: javascript three.js

您好,我正在使用二十面体测量法。在那里我将CircleGeometry添加到它的每个顶点。所以现在我的要求是当鼠标移向圆圈时,圆圈应该感应到鼠标移动并且应该朝向鼠标移动。因此,我已经围绕圆圈创建了一个RingGeometry。因此,如果鼠标移向环,则圆圈应检测鼠标的位置。

但是我无法获得鼠标位置。我使用raycaster,还有其他方法可以找到鼠标的位置吗?

3 个答案:

答案 0 :(得分:4)

Raycaster是标准的方式:

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/

答案 1 :(得分:1)

你正在寻找这样的东西吗?

var cursorX;
var cursorY;
document.onmousemove = function(e){
    cursorX = e.pageX;
    cursorY = e.pageY;
}
setInterval("checkCursor()", 1000);
function checkCursor(){
    alert("Cursor at: " + cursorX + ", " + cursorY);
}

答案 2 :(得分:0)

我做了以下(为简洁起见省略了一些部分):

// 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 + ")");
}

请查看this以获取完整代码