1

I want to move the camera every frame automatic in the z-axis in Scenekit. I have write this code in Swift:

func renderer(_ renderer: SCNSceneRenderer,
              updateAtTime time: TimeInterval) {
cameraNode.position.z = cameraNode.position.z + 2            
}

This works only for 3 frames, after that the camera doesn't move anymore. Can someone give me the correct code so the camera moves automatic every frame?

Johan Kornet
  • 103
  • 11

1 Answers1

0

According to SceneKit documentation:

SceneKit calls this method exactly once per frame, so long as the SCNView object (or other SCNSceneRenderer object) displaying the scene is not paused.

If nothing else in your view is moving, the scene is ‘paused’ and does not render. According to this question, in order to force the render every frame, the workaround should be:

sceneView.loops = true

However, updating the position every frame is not the best practice because FPS can change, which would affect the camera speed. But you can keep a consistent camera speed using SCNAction without using the render function:

let move = SCNAction.moveBy(x: 0, y: 0, z: 120, duration: 1.0)
let moveForever = SCNAction.repeatActionForever(move)
cameraNode.runAction(moveForever)

This will also make controlling your camera easier if it needs to stop, and it does not force the render if it is unnecessary.

Michael
  • 1,115
  • 9
  • 24
  • I works, but why is the code without moveyBy working with the update(....) function in Spritekit and not with the renderer function in Scenekit? – Johan Kornet Mar 11 '18 at 20:31
  • Can you add a print function with a time stamp or something just to make sure it’s being called. Also, if your FPS is not constant, your camera speed will change, but with SCNAction, the speed will be fixed – Michael Mar 11 '18 at 20:56
  • I can make a print function and I see it's called for 3 times, after that the function isn't called anymore. – Johan Kornet Mar 12 '18 at 20:41
  • I updated the answer. Is this what you are looking for? – Michael Mar 14 '18 at 19:14
  • Yes, this is also what I thought. – Johan Kornet Mar 17 '18 at 12:18