【发布时间】:2018-02-06 06:39:57
【问题描述】:
我一直在用 SceneKit 开发一个游戏,其中涉及一个用户可以使用箭头键控制的飞机。飞机可以飞,但是方向键对飞机没有影响。当我运行测试以查看箭头键功能是否正常工作时,我可以看到箭头键有效地改变了飞机的速度,但飞机并没有增加或减少速度。代码如下:
import SceneKit
import QuartzCore
class GameViewController: NSViewController {
var height = 0
var speed = 0 //I should be able to change this value by pressing the up arrow key during the simulation
override func keyDown(with theEvent: NSEvent) {
if(theEvent.keyCode == 123){//left
}
if(theEvent.keyCode == 124){//right
}
if(theEvent.keyCode == 125){//down
}
if(theEvent.keyCode == 126){//up
speed+=1
print(speed)
}
}
override func viewDidLoad(){
super.viewDidLoad()
let scene = SCNScene(named: "art.scnassets/Plane.scn")!
let cameraNode = scene.rootNode.childNode(withName: "camera", recursively: true)!
let plane = scene.rootNode.childNode(withName: "plane", recursively: true)!
plane.runAction(SCNAction.repeatForever(SCNAction.moveBy(x: 0, y: CGFloat(height), z: CGFloat(speed), duration: 1)))
cameraNode.runAction(SCNAction.repeatForever(SCNAction.moveBy(x:0, y:CGFloat(height), z: CGFloat(speed), duration:1)))
let scnView = self.view as! SCNView
}
}
【问题讨论】:
-
在场景中使用按键事件,而不是在视图控制器中。
-
当我将 keyDown 的函数移动到 viewDidLoad 函数中并从 keyDown 函数中删除覆盖时,计算机根本不响应按键。如果保留覆盖部分,则计算机返回错误。
-
哎呀!?您的场景视图有 viewDidLoad?只有视图控制器有 viewDidLoad。
-
读取事件是视图(NSView、SCNView...)的工作。
-
那么让我看看你的场景视图。