如何缩放SCNNodes以适合边界框

时间:2018-02-21 18:39:36

标签: ios swift 3d scenekit 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

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

例如,此对象可以正确缩放(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)

这个没有(篮球运动员):

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)

截图:

正确缩放

Correct image

缩放率不正确

Incorrect image

1 个答案:

答案 0 :(得分:0)

所以我最终要做的事情有所不同,因为我想将资产缩放到恰好参考大小。

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

Bounding Box as listed in Scene graph, node inspector tab

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

reference image size

  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

我写了这篇文章,因为我对这种情况非常困惑,希望它能对某人有所帮助。