In mymacCatalyst应用程序,我试图使一个SCNScene
,用户应该能够四处移动(与w,a,s和d),但它不起作用。我希望
- 让玩家可以先在场景中移动
- ,然后调整到相机面对的方向
但是第一步我已经失败了。
我试图将SCNView的观点设置为一个新的SCNNode,并试图移动它:
// initializing the scene
let scene = SCNScene(named: "SceneKit Scene.scn")!
sceneView.scene = scene
// try to set the point of the scene
let node = SCNNode()
node.position = SCNVector3(x: 10, y: 10, z: 10)
sceneView.pointOfView = node
但这并没有改变什么。
我还尝试移动节点(这是保持场景周围的所有其他节点)
override func pressesBegan(_ presses: Set<UIPress>,
with event: UIPressesEvent) {
guard let press = presses.first else { return }
guard let key = press.key else { return }
if key.charactersIgnoringModifiers == "w" {
node.position.z += 1
}
}
哪个更适合,但在场景中感觉不像在走动,如果我在相机的朝向周围移动,我就会移动到错误的方向。
那么我如何解决这个问题呢?
W 的 S D
键运动尝试这种方法(它在macOS应用程序上完美工作,但我没有在macCatalyst应用程序上测试它):
import SceneKit
class GameViewController: NSViewController {
var sceneView = SCNView(frame: .zero)
let scene = SCNScene(named: "ship.scn")!
let cameraNode = SCNNode()
override func keyDown(with event: NSEvent) {
for char in event.characters! {
switch char {
case "w" : cameraNode.position.z -= 0.5
print("Camera Moves Forward")
case "s" : cameraNode.position.z += 0.5
print("Camera Moves Backward")
case "a" : cameraNode.position.x -= 0.5
print("Camera Moves Left")
case "d" : cameraNode.position.x += 0.5
print("Camera Moves Right")
default : break
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
sceneView = self.view as! SCNView
sceneView.scene = scene
sceneView.allowsCameraControl = false
cameraNode.camera = SCNCamera()
cameraNode.position.z = 10.0
sceneView.pointOfView = cameraNode
sceneView.scene?.rootNode.addChildNode(cameraNode)
}
}
也可以使用keyCode实例属性:
override func keyDown(with event: NSEvent) {
let code: UInt16 = event.keyCode
if code == 13 {
cameraNode.position.z -= 0.5; print("Camera Moves Forward")
} else if code == 1 {
cameraNode.position.z += 0.5; print("Camera Moves Backward")
} else if code == 0 {
cameraNode.position.x -= 0.5; print("Camera Moves Left")
} else if code == 2 {
cameraNode.position.x += 0.5; print("Camera Moves Right")
}
}