我最近问了一个有一个非常明显答案的
question.我还在研究同一个项目并遇到另一个问题.我需要实现每帧逻辑,并且SCNSceneRendererDelegate协议在iOS上工作得很好,但在OSX上,渲染器函数没有触发.我创建了一个示例项目来说明我的问题.它由storyboard中的Scene Kit视图和ViewController类中的以下代码组成:
原文链接:https://www.f2er.com/swift/319866.htmlimport Cocoa import SceneKit class ViewController: NSViewController,SCNSceneRendererDelegate { @IBOutlet weak var sceneView: SCNView! let cubeNode = SCNNode() override func viewDidLoad() { super.viewDidLoad() let scene = SCNScene() let sphere = SCNSphere(radius: 0.1) sphere.firstMaterial!.diffuse.contents = NSColor.yellowColor() let sphereNode = SCNNode(geometry: sphere) scene.rootNode.addChildNode(sphereNode) let cube = SCNBox(width: 0.2,height: 0.2,length: 0.2,chamferRadius: 0) cube.firstMaterial!.diffuse.contents = NSColor.greenColor() cubeNode.geometry = cube cubeNode.position = SCNVector3(1,0) scene.rootNode.addChildNode(cubeNode) let cameraNode = SCNNode() cameraNode.camera = SCNCamera() cameraNode.position = SCNVector3(2,1,2) let constraint = SCNLookAtConstraint(target: cubeNode) cameraNode.constraints = [constraint] scene.rootNode.addChildNode(cameraNode) sceneView.scene = scene sceneView.backgroundColor = NSColor(red: 0.5,green: 0,blue: 0.3,alpha: 1) sceneView.allowsCameraControl = true sceneView.delegate = self sceneView.playing = true } func renderer(renderer: SCNSceneRenderer,updateAtTime time: NSTimeInterval) { cubeNode.position.x += 0.1 } }
我想要的只是基本上每帧移动立方体.但没有任何反应.奇怪的是,当我将sceneView.allowsCameraControl设置为true时,每当我在屏幕上单击或拖动时都会调用渲染器函数(这是有意义的,因为它需要根据摄像机角度更新视图).但我希望每一帧都能调用它.
编辑:
我已经尝试按照下面的答案中的说明,现在有ViewController的以下代码:
import Cocoa import SceneKit class ViewController: NSViewController { @IBOutlet weak var sceneView: SCNView! let scene = MyScene(create: true) override func viewDidLoad() { super.viewDidLoad() sceneView.scene = scene sceneView.backgroundColor = NSColor(red: 0.5,alpha: 1) sceneView.allowsCameraControl = true sceneView.delegate = scene sceneView.playing = true } }
和MyScene课程:
import Foundation import SceneKit final class MyScene: SCNScene,SCNSceneRendererDelegate { let cubeNode = SCNNode() convenience init(create: Bool) { self.init() let sphere = SCNSphere(radius: 0.1) sphere.firstMaterial!.diffuse.contents = NSColor.yellowColor() let sphereNode = SCNNode(geometry: sphere) rootNode.addChildNode(sphereNode) let cube = SCNBox(width: 0.2,0) rootNode.addChildNode(cubeNode) let cameraNode = SCNNode() cameraNode.camera = SCNCamera() cameraNode.position = SCNVector3(2,2) let constraint = SCNLookAtConstraint(target: cubeNode) cameraNode.constraints = [constraint] rootNode.addChildNode(cameraNode) } @objc func renderer(aRenderer: SCNSceneRenderer,updateAtTime time: NSTimeInterval) { cubeNode.position.x += 0.01 } }
但是,它仍然无法正常工作.我究竟做错了什么?
编辑:设置sceneView.loops = true修复了描述的问题