【发布时间】:2025-12-22 05:50:06
【问题描述】:
我在SCNView 中有一个圆柱体作为SCNCylinder。我想将圆柱体旋转多个给定的角度。我正在使用 SwiftUI 提供所需的输入(旋转角度)。假设我给它一个输入 90° 。目前它可以轻松旋转 90°,但如果我给它第二个输入 180°,它会回到原来的位置,然后旋转 180°。我希望它从旋转 90° 后的位置旋转 180°。
这是我的代码:
struct ContentView: View {
@State var rotationAngle: Float = 0
var body: some View {
VStack{
Text("180°").onTapGesture {
self.rotationAngle = 180.0
}
Divider()
Text("90°").onTapGesture {
self.rotationAngle = 90.0
}
SceneKitView(angle: $rotationAngle)
.position(x: 225.0, y: 175)
.frame(width: 300, height: 300, alignment: .center)
}
}
}
struct SceneKitView: UIViewRepresentable {
@Binding var angle: Float
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>) {
sceneView.scene?.rootNode.enumerateChildNodes { (node, stop) in
node.removeFromParentNode() }
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 rotation = SCNAction.rotate(by: self.degreesToRadians(self.angle),
around: SCNVector3(1, 0, 0), duration: 5)
cylindernode.runAction(rotation)
sceneView.scene?.rootNode.addChildNode(cylindernode)
}
无论我给它多少角度,我都希望它能够正确旋转。
【问题讨论】: