如何缩放SCNNodes以适合边界框

Sea*_*len 7 3d ios scenekit swift arkit

我正在下载Collada DAE场景并在SceneKit中渲染它们,但无法让下载的节点"适应"其父节点.我主要关心缩放它的y高度以适应父节点.

这是我正在使用的代码:

// Reset everything
node.position = SCNVector3(0, 0, 0)
node.pivot = SCNMatrix4Identity
node.scale = SCNVector3(1, 1, 1)

// Calculate absolute bounding box
let (min, max) = node.boundingBox
let size = max - min

// Get the biggest dimension of the node
guard let scaleRef = [size.x, size.y, size.z].max() else {
    return
}

// Desired bounding box is of size SCNVector3(0.4, 0.4, 0.4)
let parentSize: Float = 0.4

let ratio = (parentSize/scaleRef)
node.scale = SCNVector3(node.scale.x * ratio, node.scale.y * ratio, node.scale.z * ratio)

//Correctly position the node at the bottom of its parent node by setting pivot
let (minNode, maxNode) = node.boundingBox

let dx = (maxNode.x - minNode.x) / 2
let dy = minNode.y
let dz = (maxNode.z - minNode.z) / 2
node.pivot = SCNMatrix4Translate(node.pivot, dx, dy, dz)

node.position.x = dx * ratio
node.position.y = dy * ratio
node.position.z = dz * ratio
Run Code Online (Sandbox Code Playgroud)

这似乎适用于大多数情况,但我最终会得到一些不正确的缩放.

例如,此对象可以正确缩放(Poly Astornaut):

MIN: SCNVector3(x: -1.11969805, y: -0.735845089, z: -4.02169418)
MAX: SCNVector3(x: 1.11969805, y: 0.711179018, z: 0.0)
NEW SCALE: SCNVector3(x: 0.099460572, y: 0.099460572, z: 0.099460572)
Run Code Online (Sandbox Code Playgroud)

这一个不(篮球运动员):

MIN: SCNVector3(x: -74.8805618, y: 0.0459594727, z: -21.4300499)
MAX: SCNVector3(x: 74.8805618, y: 203.553589, z: 15.6760511)
NEW SCALE: SCNVector3(x: 0.00196552835, y: 0.00196552835, z: 0.00196552835)
Run Code Online (Sandbox Code Playgroud)

截图:

正确缩放

正确的形象

缩放不正确

图像不正确

Gre*_*ton 4

所以我最终做的有点不同,因为我想将我的资源缩放到精确的参考大小。

  1. 在我的.scn文件中,转到“节点检查器”选项卡并查看我正在使用的资产的边界框:

场景图、节点检查器选项卡中列出的边界框

  1. 了解参考图像的尺寸。这是您应该在现实世界中测量的内容,并将其输入到您的 Assets.xcassets 资源中

参考图像尺寸

  1. 该参考图像大小在函数中传递给您func renderer(_ renderer: SCNSceneRenderer, didAdd node: SCNNode, for anchor: ARAnchor)。我通过以下代码访问我的:

guard let imageAnchor = anchor as? ARImageAnchor else { return } let referenceImage = imageAnchor.referenceImage print(referenceImage.physicalSize.width) print(referenceImage.physicalSize.height)

  1. 无论您想要在何处缩放,您只需使用代数即可将边界框大小缩放到所需的大小。所以我们的规模很简单

let threeDimensionalAssetToRealReferenceImageScale = referenceImageWidth / threeDimensionalAssetBoundingBoxWidth

  1. 致电scale您的SCNNode

因为我对这种情况感到非常困惑,所以我写了这篇文章,希望对大家有所帮助。