How to get the center vertex position of all the faces of BoxGeometry in threejs?

325 Views Asked by At

I have a BoxGeometry here, which forms a cube, what i want to acheive is to get the center vertex position of all the faces of the cube?

const boxGeometry = new THREE.BoxGeometry(1.5,1.5,1.5,2,2,2);
const material = new THREE.MeshBasicMaterial({
      color:0xffffff,
      wireframe:true,
});
const mesh = new THREE.Mesh(boxGeometry,material);

This is the cube i'm working on

Can anyone help me figure out this?

1

There are 1 best solutions below

4
prisoner849 On

Each face is defined by a triplet of indices of vertices.

As an option to find centers:

let centers = [];
let a = new THREE.Vector3(), b = new THREE.Vector3(), c = new THREE.Vector3();
let pos = boxGeometry.attributes.position;
let idx = boxGeometry.index;
let faces = idx.count / 3;
for(let i = 0; i < faces; i++){
  a.fromBufferAttribute(pos, idx.getX(i * 3 + 0));
  b.fromBufferAttribute(pos, idx.getX(i * 3 + 1));
  c.fromBufferAttribute(pos, idx.getX(i * 3 + 2));
  a.add(b).add(c).divideScalar(3); // center is the average of three vertices
  centers.push(a.clone());
}