I have been attempting to find the centroid of a polygon in 3D space and then convert its vertices to 2D screen coordinates. Unfortunately, the code I currently have is not producing the desired results. I would greatly appreciate any assistance with this problem.
//calculate the centroid
var centroid = new THREE.Vector3();
for (var i = 0; i < positions.length; i++) {
centroid.add(positions[i]);
}
centroid.multiplyScalar(1 / positions.length);
//focus camera on centroid
var camera = new THREE.PerspectiveCamera(75, width / height, 0.1, 1000);
camera.lookAt(centroid);
//calculate the screen coordinates
for (var i = 0; i < positions.length; i++) {
screenPositions.push(convertToScreenXY(positions[i], camera, width, height));
}
function convertToScreenXY(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
};
}
It seems that the camera transformations are not being applied correctly to the projection.