提供3D虚拟内容与场景套件 使用SceneKit为您的AR体验添加逼真的三维对象

概观

要将SceneKit内容放在增强现实中,您首先需要运行AR会话(请参阅构建基本的AR体验)。

因为ARKit会将SceneKit空间自动匹配到现实世界中,所以放置一个虚拟对象,以使其看起来保持真实的位置,这要求您适当地设置对象的SceneKit位置。例如,在默认配置中,以下代码将10厘米立方体放置在相机初始位置前20厘米处:

let cubeNode = SCNNode(geometry: SCNBox(width: 0.1, height: 0.1, length: 0.1, chamferRadius: 0))
cubeNode.position = SCNVector3(0, 0, -0.2) // SceneKit/AR coordinates are in meters
sceneView.scene.rootNode.addChildNode(cubeNode)

上面的代码直接在视图的SceneKit场景中放置一个对象。该对象自动显示为跟踪真实世界的位置,因为ARKit将SceneKit空间与现实世界空间相匹配。

或者,您可以使用ARAnchor该类来跟踪现实世界的位置,无论是通过自己创建锚点并将其添加到会话或通过观察ARKit自动创建的锚点。例如,当启用平面检测时,ARKit会为每个检测到的平面添加并更新锚点。要为这些锚点添加可视化内容,请执行以下方法:ARSCNViewDelegate

func renderer(_ renderer: SCNSceneRenderer, didAdd node: SCNNode, for anchor: ARAnchor) {
    // This visualization covers only detected planes.
    guard let planeAnchor = anchor as? ARPlaneAnchor else { return }

    // Create a SceneKit plane to visualize the node using its position and extent.
    let plane = SCNPlane(width: CGFloat(planeAnchor.extent.x), height: CGFloat(planeAnchor.extent.z))
    let planeNode = SCNNode(geometry: plane)
    planeNode.position = SCNVector3Make(planeAnchor.center.x, 0, planeAnchor.center.z)

    // SCNPlanes are vertically oriented in their local coordinate space.
    // Rotate it to match the horizontal orientation of the ARPlaneAnchor.
    planeNode.transform = SCNMatrix4MakeRotation(-Float.pi / 2, 1, 0, 0)

    // ARKit owns the node corresponding to the anchor, so make the plane a child node.
    node.addChildNode(planeNode)
}

遵循设计3D资产的最佳做法

  • 使用SceneKit物理基础的照明模型,以获得更逼真的外观。(请参阅SceneKit示例代码项目中SCNMaterial类和Badger:Advanced Rendering)。

  • 烘烤环境遮挡阴影,使物体在各种场景照明条件下正常亮起。

  • 如果您创建一个虚拟对象,您打算放置在AR的真实平面上,请在3D素材中的对象下方包含一个透明平面,并具有柔和的阴影纹理。

猜你喜欢

转载自blog.csdn.net/sinat_23907467/article/details/76229508
今日推荐