Hi, im trying to calculate the uvs for a polygon, which is at a random position where plane has an angle 90° to the center vector, and also not exactly flat, but almost. I have a shader which then applies textures to multiple polygons.
So i need to translate it to the center and then rotate it sich that the plane matches an axis. Then calculate uvs such that the polygon is inside the square texture
This is the code i have:
const polyVertices = [];
const center = new THREE.Vector3().copy(t.averagePosition);
t.corners
.map(c => c.position)
.forEach((c, i, arr) => {
polyVertices.push(c.x, c.y, c.z);
polyVertices.push(t.averagePosition.x, t.averagePosition.y, t.averagePosition.z);
const next = arr[i + 1] || arr[0];
polyVertices.push(next.x, next.y, next.z);
colors.push(col, col, col);
});
const dir = new THREE.Vector3(0,1,0);
const polyGeometry = new THREE.BufferGeometry();
polyGeometry.addAttribute('position', new THREE.BufferAttribute(new Float32Array(polyVertices), 3));
const mesh = new THREE.Mesh(polyGeometry);
mesh.quaternion.setFromUnitVectors(center.clone().normalize(), dir.clone().normalize());
const box = new THREE.Box3();
box.setFromObject(mesh);
const size = box.getSize();
polyGeometry.translate(-center.x, -center.y, -center.z)
polyGeometry.translate(size.x/2, size.y/2, size.z / 2)
const verts = polyGeometry.getAttribute('position');
for (let i = 0; i < verts.array.length; i += 3) {
const v = new THREE.Vector3().fromBufferAttribute(verts, i);
mesh.localToWorld(v);
uvs.push(v.x / size.x, v.z / size.z);
}
});
But if i just set the uvs to
uvs.push(...[
0.0, 0.0,
1.0, 0.0,
1.0, 1.0,
0.0, 1.0,
]);
It works, but looks weird