簡體   English   中英

iOS SpriteKit - 游戲開始前的倒計時?

[英]iOS SpriteKit - countdown before game starts?

剛剛使用Swift進入iOS上的SpriteKit。 我在教程中有一個'Breakout'游戲,我希望在每個球發射之前實現倒計時,在屏幕中間放置一個SKLabel,從5到1倒數,然后自行移動並開始游戲。 倒計時正在進行中,你可以看到完整的游戲畫面,包括牆壁,固定球等。

我無法解決游戲循環中的位置。 如果我在didMoveToView(我創建牆並初始化球和槳)的倒計時,我從來沒有看到它,但我在日志中看到我的調試消息。 我想在呈現SKScene之前調用了didMoveToView。

我試圖在第一次調用“更新”時使用一個標志來調用倒計時功能,但我再次看到在屏幕上出現任何內容之前執行了倒計時 - 我認為在渲染場景之前最初會調用“更新”。

我可以在另一個SKScene中實現“點按屏幕開始”屏幕,但我真的想在屏幕上倒計時,牆壁和(靜止)球准備好了。 我可以使用游戲畫面的背景圖像創建這個倒計時場景,但這看起來很尷尬。

感激地收到任何建議,

史蒂夫

添加了這些函數,並在didMoveToView結束時調用了countdown(5)

func countdown(count: Int) {
    countdownLabel.horizontalAlignmentMode = .Center
    countdownLabel.verticalAlignmentMode = .Baseline
    countdownLabel.position = CGPoint(x: size.width/2, y: size.height*(1/3))
    countdownLabel.fontColor = SKColor.whiteColor()
    countdownLabel.fontSize = size.height / 30
    countdownLabel.zPosition = 100
    countdownLabel.text = "Launching ball in \(count)..."

addChild(countdownLabel)

let counterDecrement = SKAction.sequence([SKAction.waitForDuration(1.0),
    SKAction.runBlock(countdownAction)])

runAction(SKAction.sequence([SKAction.repeatAction(counterDecrement, count: 5),
    SKAction.runBlock(endCountdown)]))

}

func countdownAction() {
    count--
    countdownLabel.text = "Launching ball in \(count)..."
}

func endCountdown() {
    countdownLabel.removeFromParent()
    ball.physicsBody!.applyImpulse(CGVectorMake(20, 20))
}

因此,我創建並設置倒計時的文本,然后創建並運行等待1秒的SKAction,然后再減少倒計時並更新標簽。 它重復這5次,然后刪除倒計時標簽,最后給球一個沖動,開始它移動,所以游戲本身可以開始。

似乎工作正常......

這就是NSTimer真正派上用場的地方。 NSTimer基本上每隔一段時間激活一個函數(你指定的頻率)。

更新:有時最好不要使用NSTimer; 見這里: https//stackoverflow.com/a/24950982/5700898

這是使用NSTimer的代碼示例:

class ViewController: UIViewController {
var countdownTime = 5
var countdownTimer = NSTimer()
// above, setting your timer and countdown time as global variables so they can be accessed in multiple functions.

func PlayerPressesStart() {
countdownTime = 5
countdownTimer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "Countdown", userInfo: nil, repeats: true) // calls the function "Countdown" every second.
}

func Countdown() { // this is the function called by the timer every second, which causes your "countdownTime" to go down by 1. When it reaches 0, it starts the game.
countdownTime--
if countdownTime > 0 {
countdownTimer.invalidate()
placewhereyoudisplaycountdown.text = String(countdownTime)
}
if countdownTime == 0 {
// call the function where game action begins here, or call the function that makes the game begin here.
}
} // closing bracket for the View Controller, don't include this if you're copying and pasting to your already existing View Controller.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM