代码之家  ›  专栏  ›  技术社区  ›  Cesare

将平面节点垂直和水平添加到arkit场景

  •  2
  • Cesare  · 技术社区  · 6 年前

    我希望我的应用程序将节点放在表面上,可以是垂直的,也可以是水平的。但是,节点总是垂直的。这是一张图片,这些节点没有正确放置。

    enter image description here

    @objc func didTapAddButton() {
        let screenCentre = CGPoint(x: self.sceneView.bounds.midX, y: self.sceneView.bounds.midY)
        let arHitTestResults: [ARHitTestResult] = sceneView.hitTest(screenCentre, types: [.featurePoint]) // Alternatively, we could use '.existingPlaneUsingExtent' for more grounded hit-test-points.
        if let closestResult = arHitTestResults.first {
            let transform: matrix_float4x4 = closestResult.worldTransform
            let worldCoord: SCNVector3 = SCNVector3Make(transform.columns.3.x, transform.columns.3.y, transform.columns.3.z)
            if let node = createNode() {
                sceneView.scene.rootNode.addChildNode(node)
                node.position = worldCoord
            }
        }
    }
    
    func createNode() -> SCNNode? {
        guard let theView = myView else {
            print("Failed to load view")
            return nil
        }
    
        let plane = SCNPlane(width: 0.06, height: 0.06)
        let imageMaterial = SCNMaterial()
        imageMaterial.isDoubleSided = true
        imageMaterial.diffuse.contents = theView.asImage()
        plane.materials = [imageMaterial]
        let node = SCNNode(geometry: plane)
        return node
    }
    

    应用程序可以看到地面,但节点仍然与我们平行。我怎么修这个?

    编辑:我想我可以用 node.eulerAngles.x = -.pi / 2 这可以确保平面是水平放置的,但它在垂直表面上仍然是水平的。

    1 回复  |  直到 6 年前
        1
  •  0
  •   Cesare    6 年前

    解决了的!以下是如何使视图始终与相机“平行”的方法:

    let yourNode = SCNNode()
    
    let billboardConstraint = SCNBillboardConstraint()
    billboardConstraint.freeAxes = [.X, .Y, .Z]
    yourNode.constraints = [billboardConstraint]
    

    guard let currentFrame = sceneView.session.currentFrame else {return nil}
    let camera = currentFrame.camera
    let transform = camera.transform
    var translationMatrix = matrix_identity_float4x4
    translationMatrix.columns.3.z = -0.1
    let modifiedMatrix = simd_mul(transform, translationMatrix)
    let node = SCNNode(geometry: plane)
    node.simdTransform = modifiedMatrix