I have tried to make a text string (SCNText) fit inside a box (SCNBox) in the code below. The size of the box looks correct but the text is not in the right center of the bo
To find the center of the bounding box you need to add (not subtract) the min and max before you divide by 2.
textNode.position = SCNVector3(x: (minVec.x + maxVec.x) / 2, y: minVec.y + maxVec.y, z: 0)
The difference of SCNText from other geometries is that SCNText origin point positioned at bottom left corner. In other geometries, it is a bottom center.
To fix text position in parent node you can set its pivotPoint.x to half of width:
SCNVector3 min, max;
[textNode getBoundingBoxMin:&min max:&max];
textNode.pivot = SCNMatrix4MakeTranslation((max.x - min.x) / 2, 0, 0);
To fix subnodes position, you should set their position to half of width plus min:
SCNVector3 min, max;
[textNode getBoundingBoxMin:&min max:&max];
subnode.position = SCNVector3Make((max.x - min.x) / 2 + min.x, (max.y - min.y) / 2 + min.y, 0);
I think you might be getting bitten by SCNText's unusual treatment of origin. IIRC the Y zero is at the string's baseline, not at the bottom of the descenders.
Turn on showBoundingBoxes
In the debugOptions
and see if that helps.
Swift: center text-node in parent-node correctly
let (min, max) = textNode.boundingBox
let dx = min.x + 0.5 * (max.x - min.x)
let dy = min.y + 0.5 * (max.y - min.y)
let dz = min.z + 0.5 * (max.z - min.z)
textNode.pivot = SCNMatrix4MakeTranslation(dx, dy, dz)
let textNodeParent = SCNNode()
textNodeParent.addChildNode(textNode)