Setup async tasks for showing and hiding

This commit is contained in:
CypherPoet 2019-01-28 19:06:39 -05:00
parent c7f2c37ca0
commit 2e2246134c
2 changed files with 58 additions and 9 deletions

View File

@ -14,6 +14,7 @@ let sceneHeight = 768.0
class GameScene: SKScene {
var currentScoreLabel: SKLabelNode!
var slots = [WhackSlot]()
var popupTime = 0.85
var currentScore = 0 {
didSet {
@ -21,6 +22,13 @@ class GameScene: SKScene {
}
}
var createEnemyDelay: Double {
let minDelay = popupTime / 2.0
let maxDelay = popupTime * 2.0
return Double.random(in: minDelay...maxDelay)
}
override func didMove(to view: SKView) {
setupBackground()
@ -28,6 +36,8 @@ class GameScene: SKScene {
setupSlots()
currentScore = 0
startPopupLoop()
}
@ -90,4 +100,37 @@ class GameScene: SKScene {
return positions
}
func startPopupLoop() {
DispatchQueue.main.asyncAfter(deadline: .now() + 1) { [unowned self] in
self.createEnemy()
}
}
@objc func createEnemy() {
popupTime *= 0.991
for slot in getSlotsToShow() {
slot.show(for: popupTime)
}
DispatchQueue.main.asyncAfter(deadline: .now() + createEnemyDelay) { [unowned self] in
self.createEnemy()
}
}
func getSlotsToShow() -> [WhackSlot] {
slots.shuffle()
var slotsToShow = [slots.first!]
for (idx, threshold) in [4, 8, 10, 11].enumerated() {
if Int.random(in: 0...12) > threshold {
slotsToShow.append(slots[idx + 1])
}
}
return slotsToShow
}
}

View File

@ -41,21 +41,27 @@ class WhackSlot: SKNode {
}
func show(for duration: Double) {
func show(for timeUntilHide: Double) {
guard !isShowingPenguin else { return }
isPenguinGood = Double.random(in: 0...1) >= 0.3333
penguinNode.run(SKAction.moveBy(x: 0, y: 80, duration: 0.05))
showPenguin(for: duration)
}
private func showPenguin(for duration: Double) {
let showAction = SKAction.moveBy(x: 0, y: 80, duration: 0.05)
penguinNode.run(showAction)
isShowingPenguin = true
isWhacked = false
DispatchQueue.main.asyncAfter(deadline: .now() + (timeUntilHide * 3.5)) { [unowned self] in
self.hide()
}
}
func hide() {
guard isShowingPenguin else { return }
penguinNode.run(SKAction.moveBy(x: 0, y: -80, duration: 0.05))
isShowingPenguin = false
}