enumerateChildNodes在sprite工具包中找不到子节点 - Swift 4

时间:2018-02-07 21:15:39

标签: swift sprite-kit

我正在尝试创建一个SpriteKit游戏,其中一个球在屏幕上移动。当球离开屏幕时,我想将其从父节目中移除并切换到另一个场景(GameOverScene)。

我正在使用enumerateChildNodes,但它并不像是在运作。我不确定问题是什么,但我认为它可能与父母/子女关系有关...

func createBall(forTrack track: Int) {

    setupTracks()

    player?.physicsBody?.linearDamping = 0

    player = SKSpriteNode(imageNamed: "small")
    player?.name = "BALL"
    player?.size = CGSize(width: 100, height: 100)
    ballValue = 1
    randFloat = Float(arc4random()) / Float(UINT32_MAX)

    if randFloat > 0.001 {
        ballSpeed = randFloat / 50
    }
    else {
        ballSpeed = randFloat / 50
    }

    let ballPosition = trackArray?[track].position

    player?.position = CGPoint(x: (ballPosition?.x)!, y: (ballPosition?.y)!)
    player?.position.y = (ballPosition?.y)!

    if ballDirection == "right" {
        player?.position.x = 0
        moveRight()
    }
    else {
        player?.position.x = (self.view?.frame.size.height)!
        moveLeft(speed: ballSpeed)
    }

    self.addChild(player!)

    self.enumerateChildNodes(withName: "BALL") { (node: SKNode, nil) in
        if node.position.x < -100 || node.position.x > (self.size.width) + 100 {
            print("balls Out")
            node.removeFromParent()
            let transition = SKTransition.fade(withDuration: 1)
            self.gameScene = SKScene(fileNamed: "GameOverScene")
            self.gameScene.scaleMode = .aspectFit
            self.view?.presentScene(self.gameScene, transition: transition)
        }
    }

}

我先调用此函数两次,先在override func didMove()

override func didMove(to view: SKView) {

    createHUD()
    createBall(forTrack: track)

}

override func touchesBegan中排名第二:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
        let location = touch.previousLocation(in: self)
        let node = self.nodes(at: location).first

        if node?.name == "BALL" {
            currentScore += ballValue
            player?.removeFromParent()
            createBall(forTrack: track)
        }
        else {
            let transition = SKTransition.fade(withDuration: 1)
            gameScene = SKScene(fileNamed: "GameOverScene")
            gameScene.scaleMode = .aspectFit
            self.view?.presentScene(gameScene, transition: transition)
        }
    }
}

更新

self.enumerateChildNodes(withName: "BALL") { (node: SKNode, nil) in有效,因此它不是子父关系问题。 if statement无效。

1 个答案:

答案 0 :(得分:2)

阅读你的代码我认为它不是一个解决方案,而是一个不同的方法。这些建议将使您的生活更轻松:

  1. 从较小的代码开始,避免或注释掉所有不需要的代码(如if randFloat)
  2. 强制使用解包player = SKSpriteNode(imageNamed: "small")!,因为如果初始化失败,您实际上想要崩溃,那么您可以摆脱所有?
  3. 在touchesBegan中,更好地使用for touch in touches {,因为它更易于管理
  4. let location = touch.previousLocation(in: self)您的意思可能是let location = touch.location(in: self)
  5. 当球离开屏幕时,我想将它从父母中删除,所以这是游戏中某个时候发生的事情。您希望将self.enumerateChildNodes(withName: "BALL") {拨入更新通话,而不是每次触摸屏幕时
  6. 如果这还不够,请随意发布最少量的代码来制作游乐场并让我为您测试:]