three.jsaframe

Center mesh position for text-geometry


I'm struggling with the positioning of some aframe text geometry and am wondering if I'm going about this the wrong way 😅

I'm finding that when the box renders, the center point is at the minimum point of all the axises (bottom-left-close). This means the text expands more to the top-right-far than I would expect. This is different from aframe geometry entitites where the center point is at the very center of all axises.

Sorry if the above phrasing is confusing, I'm still not sure how to best describe things in a 3d space 😆

What I'm thinking I need to do is calculate the bounding box after the element has loaded and change the position to the center. I've based that approach on the answer here AFRAME text-geometry component rotation from center?.

Does that seem like the right direction? If so, I'm currently trying to do this through an aframe component

aframe.registerComponent('center-all', {
  update() {
    // Need to wait for the element to be loaded
    setTimeout(() => {
      const mesh = this.el.getObject3D('mesh');
      const bbox = new THREE.Box3().setFromObject(this.el.object3D);
      const offsetX = (bbox.min.x - bbox.max.x) / 2;
      const offsetY = (bbox.min.y - bbox.max.y) / 2;
      const offsetZ = (bbox.min.z - bbox.max.z) / 2;
      mesh.position.set(offsetX, offsetY, offsetZ);
    }, 0);
  }
});

This code illustrates the problem I'm seeing Center at min axises

This code shows my attempted solution reposition incorrect attempt

This code (with the translation hard coded) is more like what I would like enter image description here


Solution

  • TextGeometry and TextBufferGeometry are both subclasses of the respective geometry classes, and so both have the boundingBox property. You just need to compute it, then get its center point:

    textGeo.computeBoundingBox();
    const center = textGeo.boundingBox.getCenter(new Vector3());
    

    Then center will accurately reflect the center of the geometry, in local space. If you need it in global space, you will need to apply the matrix of the mesh that contains textGeo to the center vector, e.g.

    textMesh.updateMatrixWorld();
    center.applyMatrix4(textMesh.matrixWorld);