如何使用SwiftUI更新SceneKit场景?

时间:2019-12-13 08:18:29

标签: rotation swiftui scenekit

我在SceneKit的SCNCylinder中有一个SCNScene圆柱体,并希望在SwiftUI的框架中显示它。我的目标是将圆柱体旋转180°或90°(根据用户选择)。为了获取(旋转角度)的输入,我在SwiftUI中使用了Text()onTapGesture{ .... }属性。点击文字后,圆柱体旋转,但是现在我有两个圆柱体,一个在原始位置,另一个以所需的角度旋转。我不知道为什么会这样。我希望同一个圆柱体旋转,而不是相同的副本。我已经使用@State@Binding连接了SwiftUI视图和SceneKit视图。

这是我的代码:

struct ContentView: View {
 @State var rotationAngle = 0

var body: some View {

    VStack{

        Text("180°").onTapGesture {
            self.rotationAngle = 180
        }

        Spacer()

        Text("90°").onTapGesture {
            self.rotationAngle = 90
        }

        SceneKitView(angle: $rotationAngle)
            .position(x: 225.0, y: 200)
            .frame(width: 300, height: 300, alignment: .center)

    }
  }
}

struct SceneKitView: UIViewRepresentable {

 @Binding var angle: Int

func degreesToRadians(_ degrees: Float) -> CGFloat {
    return CGFloat(degrees * .pi / 180)
}

func makeUIView(context: UIViewRepresentableContext<SceneKitView>) -> SCNView {

    let sceneView = SCNView()
    sceneView.scene = SCNScene()
    sceneView.allowsCameraControl = true
    sceneView.autoenablesDefaultLighting = true
    sceneView.backgroundColor = UIColor.white
    sceneView.frame = CGRect(x: 0, y: 10, width: 0, height: 1)

    return sceneView
}

func updateUIView(_ sceneView: SCNView, context: UIViewRepresentableContext<SceneKitView>) {

        let cylinder = SCNCylinder(radius: 0.02, height: 2.0)
        let cylindernode = SCNNode(geometry: cylinder)
        cylindernode.position = SCNVector3(x: 0, y: 0, z: 0)
        cylinder.firstMaterial?.diffuse.contents = UIColor.green

        cylindernode.pivot = SCNMatrix4MakeTranslation(0, -1, 0)

        let inttofloat = Float(self.angle)

         let rotation = SCNAction.rotate(by: self.degreesToRadians(inttofloat), around: SCNVector3(1, 0, 0), duration: 5)

         cylindernode.runAction(rotation)

         sceneView.scene?.rootNode.addChildNode(cylindernode)

}
typealias UIViewType = SCNView

}

我想以给定角度进行一次圆柱旋转。

1 个答案:

答案 0 :(得分:1)

问题是,updateUIView将被调用多次。您可以通过在其中添加调试点来进行检查。因此,您的圆柱体将被添加几次。因此,您可以通过多种方法解决此问题...一种方法是像这样在开始动画之前删除场景视图中的所有节点:

SharedViewModel