三JS投影问题

Three JS Projection Issue

本文关键字:问题 投影 JS      更新时间:2023-09-26

我试图在3d空间中查看多边形的中心,然后将其点转换为2d屏幕坐标。这就是不起作用的代码。如有任何帮助,不胜感激。

//calculate the center
var center = new THREE.Vector3();
for (var i = 0; i < positions.length; i++) {
    center.add(positions[i]);
}
center.multiplyScalar(1 / positions.length);
//look at the center
var camera = new THREE.PerspectiveCamera(75, width / height, 0.1, 1000);
camera.lookAt(center);
//calculate the screen coordinates
for (var i = 0; i < positions.length; i++) {
    screenPositions.push(toScreenXY(positions[i], camera, width, height));
}
function toScreenXY(position, camera, width, height) {
    var pos = position.clone();
    pos.project(camera);
    var halfWidth = width / 2,
        halfHeight = height / 2;
    return {
        x: (pos.x + 1) * halfWidth + halfWidth,
        y: (-pos.y + 1) * halfHeight + halfHeight
    };
}

就好像摄像机的变换对投影没有影响

既然你改变了相机的旋转,你就需要更新相机的世界矩阵,因为方法project()引用了它。

camera.position.set( x, y, z );
camera.lookAt( center );
camera.updateMatrixWorld(); // add this

渲染器在renderer.render()中为你调用camera.updateMatrixWorld(),但在这种情况下,你必须自己调用它。

three.js r.71