2017-07-12 47 views
0

我正在嘗試創建一個遊戲,其中有人點擊一個框,使其消失。我的問題是'重新啓動'遊戲並重新添加所有以前隱藏/刪除的框。Scene套件(Swift):取消隱藏或重新添加隱藏/刪除的節點

我創建的箱子一排像這樣:

func addBoxes() { 

    for _ in 0..<5 { 

     let sphereGeometry = SCNBox(width: 1, height: 1, length: 1, chamferRadius: 0) 
     let sphereNode: SCNNode! = SCNNode(geometry: sphereGeometry) 
     sphereNode.position = SCNVector3(x: x, y: y, z: z) 

     scnScene.rootNode.addChildNode(sphereNode) 
} 

後,我更新的X,Y,當然z上的位置。

這一切精美的作品,我躲像挖框,以便:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { 

    let touch = touches.first! 
    let location = touch.location(in: scnView) 
    let hitResults = scnView.hitTest(location, options: nil) 

    if let result = hitResults.first { 

     let node = result.node 
     node.isHidden = true 
    } 
} 

畢竟盒竊聽和隱藏,遊戲應該簡單地重置了,所以取消隱藏所有框:

func newGame() { 

    // I've tried this and various versions of it, with no success 
    for child in scnScene.rootNode.childNodes { 

     child.isHidden = false 
    } 
} 

然而,這給了我:

fatal error: unexpectedly found nil while unwrapping an Optional value 

我也試過child.removeFromParentNode()和TH en試圖重新將節點添加到場景中,但是這會引發相同的錯誤。

任何人都可以在正確的方向指向我嗎?我如何取消隱藏在for循環中創建的一個或所有節點?

+0

您可以添加一個異常斷點來獲取崩潰的確切行嗎?我根本沒有在代碼中看到任何可選項。或者'scnScene'聲明爲'SCNScene!'? – orangenkopf

+0

@ orangenkopf:是的。它在'scnScene.rootNode.addChildNode(sphereNode)' – Harold

+0

'SCNNode(geometry:)'''不會返回一個可選項,所以你可以刪除'SCNNode'類型並讓編譯器引用類型。但是你的問題與隱藏/取消隱藏無關。相反,當你嘗試向它添加節點時,你可能沒有創建你的場景 – orangenkopf

回答

2

隱藏和取消隱藏工作正常,像這樣:

var targetsToDo: Int = 0 
let maximumNumberOfTargets = 5 

func loadGame() { 
    targetsToDo = maximumNumberOfTargets 

    scnScene = SCNScene() 
    scnView.scene = scnScene 

    for i in 1...maximumNumberOfTargets { 
     let box = SCNBox(width: 1, height: 1, length: 1, chamferRadius: 0.1) 
     let node = SCNNode(geometry: box) 
     node.name = "Box \(i)" 
     scnScene.rootNode.addChildNode(node) 
     node.position = getRandomPosition() 
    } 
} 

@objc func handleTouch(recognizer: UITapGestureRecognizer) { 
    let point = recognizer.location(in: view) 
    print("Touch at \(NSStringFromCGPoint(point))") 
    if let node = scnView.hitTest(point).first?.node { 
     print(node.name ?? "") 
     node.isHidden = true 
     targetsToDo -= 1 

     if targetsToDo == 0 { 
      resetGame() 
     } 
    } 
} 

func resetGame() { 
    targetsToDo = maximumNumberOfTargets 

    for child in scnScene.rootNode.childNodes { 
     child.isHidden = false 
     child.position = getRandomPosition() 
    } 
} 

一個完整的,工作操場可以發現here