在Sprite Kit中创建HUD,在屏幕上保持静态

时间:2015-11-06 03:55:35

标签: ios swift sprite-kit 2d-games

我正在尝试在本教程的跳转游戏中创建一个静态HUD,它在整个游戏中保持在屏幕顶部。我还是Swift的新手,所以也许这是一个我不容易看到的惯例:

http://www.raywenderlich.com/87232/make-game-like-mega-jump-sprite-kit-swift-part-2

在教程中,他将HUD置于Meteor.user().profile.avatar函数中:

override init(size: CGSize)

但是,如果我在游戏中尝试使用此功能,我会收到错误:

required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(size: CGSize) { super.init(size: size) ... // Build the HUD // HUD hudNode = SKNode() hudNode.zPosition = 1000 addChild(hudNode) // Coins // 1 let coin = SKSpriteNode(imageNamed: "powerup05_1") coin.position = CGPoint(x: 300, y: self.size.height-100) coin.zPosition = 1000 hudNode.addChild(coin) // 2 lblCoins = SKLabelNode(fontNamed: "ChalkboardSE-Bold") lblCoins.fontSize = 70 lblCoins.fontColor = SKColor.whiteColor() lblCoins.position = CGPoint(x: 375, y: self.size.height-100) lblCoins.horizontalAlignmentMode = SKLabelHorizontalAlignmentMode.Left lblCoins.zPosition = 1000 // 3 lblCoins.text = String(format: "X %d", GameState.sharedInstance.coins) hudNode.addChild(lblCoins) // Score // 4 lblScore = SKLabelNode(fontNamed: "ChalkboardSE-Bold") lblScore.fontSize = 70 lblScore.fontColor = SKColor.whiteColor() lblScore.position = CGPoint(x: self.size.width-325, y: self.size.height-100) lblScore.horizontalAlignmentMode = SKLabelHorizontalAlignmentMode.Right lblScore.zPosition = 1000 // 5 lblScore.text = "0" hudNode.addChild(lblScore) }

在此功能中:

Argument labels '(fileNamed:)' do not match any available overloads

所以我已经把它放在override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { switch gameState.currentState { case is WaitingForTap: gameState.enterState(WaitingForBomb) // Switch to playing state self.runAction(SKAction.waitForDuration(2.0), completion:{ self.gameState.enterState(Playing) }) case is GameOver: // Error! Argument labels '(fileNamed:)' do not match any available overloads let newScene = GameScene(fileNamed:"GameScene") newScene!.scaleMode = .AspectFill let reveal = SKTransition.flipHorizontalWithDuration(0.5) self.view?.presentScene(newScene!, transition: reveal) default: break } } ,但是一旦玩家跳起来,HUD会移动:

override func didMoveToView(view: SKView)

1 个答案:

答案 0 :(得分:7)

hudNode添加到cameraNode会使HUD与相机一起移动,使其在屏幕上看起来是静态的。这是将addChild(hudNode)更改为cameraNode.addChild(hudNode)

然后使用convert(_:to:)将点从当前场景坐标更改为cameraNode坐标。只需稍加修改,即可在新坐标中设置HUD的位置。例如,像这样更改coin.position

coin.position = convert(CGPoint(x: 300, y: self.size.height-100), to: cameraNode)

对另一个HUD做同样的事情:

lblCoins.position = convert(CGPoint(x: 375, y: self.size.height-100), to: cameraNode)
lblScore.position = convert(CGPoint(x: self.size.width-325, y: self.size.height-100), to: cameraNode)

修改4行后的结果:

enter image description here