【问题标题】:Placement of 3D object not working the SECOND time my button is pressed第二次按下按钮时 3D 对象的放置不起作用
【发布时间】:2023-04-05 02:42:01
【问题描述】:

我以编程方式向我的 ARSCNView 添加了一个按钮,并添加了一个在点击时调用的函数。该函数创建并放置一个 3D 对象。该按钮第一次按下时可以正常工作,但第二次之后它不会放置我的对象。

这是我的代码:

private var button = UIButton()

override func viewDidLoad() {
    super.viewDidLoad()

    // Set the view's delegate
    sceneView.delegate = self

    button.setTitle("Body", for: button.state)
    button.frame = CGRect(x: 100, y: 25, width: 100, height: 25)
    button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
    view.addSubview(button)
}

@objc func buttonAction(sender: UIButton!) {
        self.createPlaneNode()
}

func createPlaneNode() {
    //Create a new scene with our 3D object in it
    print("Hi")
    //This prints everytime the button is pressed, I checked.


    let object = SCNScene(named: "art.scnassets/manbody.obj")
    let node = SCNNode()
    let nodeArray = object!.rootNode.childNodes

    for childNode in nodeArray {
        node.addChildNode(childNode)
    }

    guard let currentFrame = sceneView.session.currentFrame else {
        return
    }
    var translation = matrix_identity_float4x4
    translation.columns.3.z = -0.1 // Translate 10 cm in front of the camera
    node.simdTransform = simd_mul(currentFrame.camera.transform, translation)

    // SCNPlanes are vertically oriented in their local coordinate space.
    // Rotate it to match the horizontal orientation of the ARPlaneAnchor.

    node.transform = SCNMatrix4MakeRotation(-Float.pi / 2, 1, 0, 0)
    sceneView.scene.rootNode.addChildNode(node)
}

【问题讨论】:

    标签: ios swift arkit


    【解决方案1】:

    第二次确实有效,检查多边形数。 ;)

    但是,您无法看到后续调用的结果,因为您一直将对象放在同一位置。

    你在这里正确设置了一个新位置:

    node.simdTransform = simd_mul(currentFrame.camera.transform, translation)
    

    但是你在下一行覆盖了转换:

    node.transform = SCNMatrix4MakeRotation(-Float.pi / 2, 1, 0, 0)
    

    请注意,node.simdTransformnode.transform 只是同一事物的不同“视图”。

    更改节点的轴心以应用旋转,或乘以变换而不是覆盖它。

    【讨论】:

    • 嗯,是的,谢谢你,我自己想通了。后续问题:如何旋转我的节点而不每次都将其放置在同一位置?
    • @Jharden13 这在我的回答的最后一行进行了解释,如果不清楚,请告诉我。
    • 哦,好吧。我只是设置我的 node.pivot = SCNMatrix4MakeRotation(-Float.pi/ 2, 1, 0, 0) 吗?
    • 是的。这样,SceneKit 会将其与引擎盖下的变换相乘以获得最终结果。
    猜你喜欢
    • 2021-03-16
    • 1970-01-01
    • 1970-01-01
    • 2020-01-23
    • 2017-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多