我正在尝试在快速的操场上做一个简单的游戏。我在SwiftUI
视图中有两个(某种)按钮,在它们下面有一个SCNView
。在这种情况下,我有一个SCNCylinder。这两个按钮是“ 90度”和“ 180度”。我只希望圆柱体围绕用户在圆柱体当前位置上选择的角度绕不同的轴旋转。在我的代码中,我使用了两个布尔变量,当分别点击相应的按钮时,它们会返回true或false。但是,当我按下任何一个按钮时,我的操场就崩溃了。 (请为我提供较长的变量名。)
我的代码是:
import UIKit
import SwiftUI
import SceneKit
import Combine
struct ContentView: View {
@State var button180DegreesIsTapped: Bool = false
@State var button90DegreesIsTapped: Bool = false
var body: some View {
VStack{
HStack{
Text("180 degrees").onTapGesture {
self.button90DegreesIsTapped = false
self.button180DegreesIsTapped = true
}
Text("90 degrees").onTapGesture {
self.button90DegreesIsTapped = true
self.button180DegreesIsTapped = false
}
}
SceneKitView(radius: 0.02, height: 2, is180DegreeTapped: $button180DegreesIsTapped, is90DegreeTapped: $button180DegreesIsTapped)
.position(x: 200.0, y: 140)
.frame(width: 300, height: 300, alignment: .center)
}
}
}
struct SceneKitView: UIViewRepresentable {
@Binding var is180DegreeTapped : Bool
@Binding var is90DegreeTapped: Bool
let cylindernode: SCNNode
init(radius: CGFloat, height: CGFloat, is180DegreeTapped : Binding<Bool>, is90DegreeTapped: Binding<Bool>) {
let cylinder = SCNCylinder(radius: radius, height: height)
cylinder.firstMaterial?.diffuse.contents = UIColor.green
self.cylindernode = SCNNode(geometry: cylinder)
self.cylindernode.position = SCNVector3(0, 0, 0)
self.cylindernode.orientation = SCNVector4(0, 0, 0, 0)
cylindernode.pivot = SCNMatrix4MakeTranslation(0, -1, 0)
self._is180DegreeTapped = is180DegreeTapped
self._is90DegreeTapped = is90DegreeTapped
}
func makeUIView(context: UIViewRepresentableContext<SceneKitView>) -> SCNView {
let sceneView = SCNView()
sceneView.scene = SCNScene()
sceneView.autoenablesDefaultLighting = true
sceneView.allowsCameraControl = true
sceneView.scene?.rootNode.addChildNode(cylindernode)
return sceneView
}
func updateUIView(_ sceneView: SCNView, context: UIViewRepresentableContext<SceneKitView>) {
if is90DegreeTapped == true && is180DegreeTapped == false{
let rotate = CABasicAnimation(keyPath: "transform.rotation")
rotate.duration = 5
rotate.isRemovedOnCompletion = true
cylindernode.addAnimation(rotate, forKey: "rotate")
cylindernode.rotate(by: SCNVector4(x: 0, y: 0, z: 0.7071, w: 0.7071), aroundTarget: SCNVector3(0, 0, 1))
cylindernode.position = SCNVector3(0, 0, 0)
}
if is180DegreeTapped == true && is90DegreeTapped == false{
let rotate = CABasicAnimation(keyPath: "transform.rotation")
rotate.duration = 5
rotate.isRemovedOnCompletion = true
cylindernode.addAnimation(rotate, forKey: "rotate")
cylindernode.rotate(by: SCNVector4(x: 1, y: 0, z: 0, w: 0), aroundTarget: SCNVector3(1, 0, 0))
cylindernode.position = SCNVector3(0, 0, 0)
}
}
}
let host = UIHostingController(rootView: ContentView())
如果我删除行self.button90DegreesIsTapped = false
和self.button180DegreesIsTapped = false
,代码将运行,但是显然不能达到预期的结果。如果是错误,请告诉我是否还有其他解决方法。请帮我解决这个问题。