ios - 如何从 collectionView 中选择项目并将其添加到 SCNScene 中?

标签 ios swift xcode augmented-reality arkit

我正在使用 SceneKit 和 ARKit。我用一系列表情符号制作了一个collectionView。现在,我希望用户能够从 collectionView 中选择表情符号,并且当他/她触摸屏幕时,所选表情符号将被放置在 3D 中。

我怎样才能做到这一点?我想我必须为 Node 创建一个函数,但我的想法仍然很模糊,我不是很清楚。

最佳答案

只要任何表情符号都是 2D 元素,最好使用 SpriteKit 框架来上传它们,而不是 SceneKit。但是,当然,您也可以选择 SceneKit。因此,您可以通过两种方式在 ARKit 中使用表情符号:

  • 使用 SpriteKit。在这种情况下,您在 ARSKView 中生成的所有 2D Sprite 始终面向相机。因此,如果相机围绕真实场景的某个确定点移动,所有 Sprite 都会围绕面向相机的枢轴点旋转。

  • 使用 SceneKit。在 ARSCNView 中,您可以使用所有 Sprite 作为 3D 几何体的纹理。该纹理可以用于平面、立方体、球体或任何自定义模型,这取决于您。例如,要制作一个面向相机的平面(上面带有表情符号纹理),请使用 SCNBillboardConstraint约束。

以下是在 ViewController 中编写代码的方式:

// Element's index coming from `collectionView`
var i: Int = 0

func view(_ view: ARSKView, nodeFor anchor: ARAnchor) -> SKNode? {
    let emojiArray = ["🐶","🦊","🐸","🐼","🐹"]
    let emojiNode = SKLabelNode(text: emojiArray[i])           
    emojiNode.horizontalAlignmentMode = .center
    emojiNode.verticalAlignmentMode = .center
    return emojiNode
}

...并在 Scene.swift 文件中:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    guard let sceneView = self.view as? ARSKView else { return }

    if let currentFrame = sceneView.session.currentFrame {
        var translation = matrix_identity_float4x4
        translation.columns.3.z = -0.75               // 75 cm from camera
        let transform = simd_mul(currentFrame.camera.transform, translation)
        let anchor = ARAnchor(transform: transform)
        sceneView.session.add(anchor: anchor)
    }
}

或者,如果您使用 HitTest ,您的代码可能如下所示:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    guard let sceneView = self.view as? ARSKView else { return }

    if let touchLocation = touches.first?.location(in: sceneView) {
        if let hit = sceneView.hitTest(touchLocation, types: .featurePoint).first {
            sceneView.session.add(anchor: ARAnchor(transform: hit.worldTransform))
        }
    }
}

如果您想创建一个包含可供选择的表情符号的 UICollectionView 叠加层,请阅读 the following post .

如果您想创建一个 SKView 叠加层,其中包含可供选择的表情符号,请阅读 the following post .

关于ios - 如何从 collectionView 中选择项目并将其添加到 SCNScene 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56510632/

相关文章:

iphone - iOS - 从 MFMailComposeViewController 中删除 UIImageView

ios - 使用 cfnetwork 写入输出流时 exc_bad_access

jquery - 此代码在 iOS 9.3 后在 Safari 中停止工作

iphone - 关于 Xcode 4 中通用应用程序的问题

ios - Swift:无法使带有部分的表中带有标识符的单元格出队

iOS 9 - Xcode : "Follows Readable Width" programmatically

ios - BlueCap Kit BLE 在 iOS 中的实现

ios - UITextField defaultTextAttributes 错误?

ios - 读取 NSTimer 子类的 public var valid 失败,错误为 'isValid only defined for abstract class'

Swift:UIRotationGesture 中手指的中心点在 SKView 中的错误位置?