SceneKit中Swift相机沿Z轴每帧自动移动失效问题求助
Hey there! It sounds like your current code is only triggering the camera movement a few times instead of every frame. The most common issue here is that you're not hooking into SceneKit's per-frame update cycle properly. Let's fix that with a reliable implementation:
Step-by-Step Correct Code
First, make sure your view controller conforms to SCNSceneRendererDelegate—this gives you access to the per-frame update callback. Here's a complete example:
import UIKit import SceneKit class ViewController: UIViewController, SCNSceneRendererDelegate { private var scnView: SCNView! private var cameraNode: SCNNode! override func viewDidLoad() { super.viewDidLoad() // Set up the SceneKit view scnView = SCNView(frame: view.bounds) scnView.autoresizingMask = [.flexibleWidth, .flexibleHeight] scnView.backgroundColor = .black view.addSubview(scnView) // Create an empty scene let scene = SCNScene() scnView.scene = scene // Create and configure the camera node cameraNode = SCNNode() cameraNode.camera = SCNCamera() cameraNode.position = SCNVector3(x: 0, y: 0, z: 10) // Starting position scene.rootNode.addChildNode(cameraNode) // Enable per-frame updates by setting the delegate scnView.delegate = self // Start the scene's animation loop scnView.play(nil) } // This method is called EVERY frame by SceneKit func renderer(_ renderer: SCNSceneRenderer, updateAtTime time: TimeInterval) { // Adjust the Z position here—negative values move the camera forward, positive moves back // Tweak the 0.1 value to change movement speed cameraNode.position.z -= 0.1 // Optional: Add a boundary to stop movement if needed // if cameraNode.position.z > -50 { // cameraNode.position.z -= 0.1 // } } }
Key Fixes & Explanations
- Per-Frame Callback: The
renderer(_:updateAtTime:)method is executed every single frame while the scene is running. This ensures your camera moves continuously, not just a few times. - Delegate Setup: You must set
scnView.delegate = self—without this, SceneKit won't call the update method. - Animation Loop: Calling
scnView.play(nil)starts SceneKit's internal animation loop, which drives the per-frame updates.
Why Your Original Code Stopped After 3 Frames
Chances are you were using a one-time SCNAction with a limited repeat count, or you were updating the camera position only in a method that runs a few times (like viewDidLoad). By moving the position logic into the per-frame delegate method, you guarantee it runs every frame.
内容的提问来源于stack exchange,提问作者Johan Kornet

