如何在THREE.Points对象中单击特定点?

时间:2017-03-19 12:34:14

标签: javascript three.js

我试图使用raycaster来确定点的2d表面上的点...

function dynamic(x) { x.dynamic = true; return x; }
geometry.addAttribute("position", dynamic(new THREE.BufferAttribute(positions, 3)));
geometry.addAttribute("color", dynamic(new THREE.BufferAttribute(colors, 3)));
var grid = new THREE.Points(geometry, material);
scene.add(grid);

function mouseDownHandler(event) {
    if (event.button == 0) {
        event.preventDefault();
        var mouse = new THREE.Vector2();
        var box = canvas.getBoundingClientRect();
        mouse.x = ((event.clientX - box.left) / (box.right - box.left)) * 2.0 - 1.0;
        mouse.y = ((event.clientY - box.bottom) / (box.top - box.bottom)) * 2.0 - 1.0;
        raycaster.setFromCamera(mouse, camera);
        var intersects = raycaster.intersectObject(grid);
        if (intersects.length > 0) {
// Why does my intersect not work?
// I _believe_ I'm calculating the mouse positions correctly.
// But, the intersects are always way off. (Or, I'm misinterpreting
// something...)
            console.log("mouse: ", mouse);
            console.log("First Intersect:", intersects[0]);
            console.log("First Point:", intersects[0].point);
        }
    }
}

我在这里有完整的代码: https://som.hex21.com/threejs/wtf/是页面,和 https://som.hex21.com/threejs/wtf/js/gridsearch.js是代码..

我的问题在于mouseDownHandler。基本上,当你点击鼠标时,我希望它告诉我点击了哪个点。但是,当我点击网格左下角的说法时,鼠标是(近){-1,-1},我认为这是预期的,对吧?)并且右上角靠近{1,1}。 / p>

我应该如何阅读点击点的索引?我点击了所有四个角点,我希望至少一个它们只是按照构造数据的方式为0。 (只有2个嵌套for循环)但是,它们永远不会,并且相交[0] .point中的点总是显得很远。我做错了什么?

谢谢!

2 个答案:

答案 0 :(得分:0)

只为其他人阅读此内容。鼠标计算很好。真正的问题是

camera = new THREE.PerspectiveCamera(fov, 1, 1e-16, 1000);

距离透视相机的最小距离太小。一旦我将其改为

camera = new THREE.PerspectiveCamera(fov, 1, 1e-2, 1000);

一切都很好。回想起来,它是有道理的,可能在某处发生某种下溢。 (你可以看到它在这里工作:     https://som.hex21.com/threejs/ftw/并且没有在此处进行单一更改:https://som.hex21.com/threejs/wtf/(两者都使用原始mouseDownHandler))

答案 1 :(得分:-1)

你的鼠标应该是:

var box = canvas.getBoundingClientRect();
var mouseX = event.clientX - box.left;
var mouseY = event.clientY - box.top;

var mouse = new THREE.Vector2 (
        2 * (mouseX / canvas.width) - 1,
    1 - 2 * (mouseY / canvas.height));

您可以在以下网址找到更多信息:http://soledadpenades.com/articles/three-js-tutorials/object-picking/