Swift 3:通过叠加SKView在SpriteKit中制作暂停菜单?
Swift 3: Making a Pause Menu in SpriteKit by overlaying a SKView?
上下文
虽然有些游戏选择放弃暂停菜单 - 推测是因为游戏持续时间短,例如 Don't Grind - 我个人认为暂停游戏是一项关键功能,我想学习如何在 SpriteKit 的 Swift 3 中实现它。
我曾看到有人尝试使用 UIAlertController
来做到这一点,但我——也许是错误的——认为更好的选择是在当前 SKView
.
我查看了 Apple 的 DemoBots,看看我是否能弄清楚他们是如何暂停游戏的。然而,在我的设备上下载并 运行 之后,它导致了错误,所以我不想效仿。但是,如果有人能彻底解释“LevelScene+Pause”、“SceneManager”、“SceneOperation”等众多文件以及它们如何协同工作,那也很酷。
问题
如何在 GameScene
上叠加 SKView
来制作暂停菜单?
最小工作示例
M.W.E.,
Whosebug SpriteKit with Menu,是一个准系统“游戏”,用于将答案语境化。请回答与 M.W.E.
有关的问题
更新
以下是 M.W.E 的修改版本。文件“GameScene”。
它考虑了为要暂停的元素添加一个主节点和为暂停菜单添加另一个节点。
虽然暂停菜单有效,但背景仍然有效,即使 gameNode.isPaused = true
。 (尝试点击最左边的蓝色精灵)。
//
// GameScene.swift
// Whosebug
//
// Created by Sumner on 1/17/17.
// Copyright © 2017 Sumner. All rights reserved.
//
import SpriteKit
import GameplayKit
class GameScene: SKScene {
var cam: SKCameraNode!
var sprite = SKSpriteNode(imageNamed: "sprite")
var sprite2 = SKSpriteNode(imageNamed: "sprite2")
let pauseLabel = SKLabelNode(text: "Pause!")
/*
*
* START: NEW CODE
*
*/
let gameNode = SKNode()
var pauseMenuSprite: SKShapeNode!
let pauseMenuTitleLabel = SKLabelNode(text: "Pause Menu")
let pauseMenuContinueLabel = SKLabelNode(text: "Resume game?")
let pauseMenuToMainMenuLabel = SKLabelNode(text: "Main Menu?")
/*
*
* END: NEW CODE
*
*/
var timeStart: Date!
init(size: CGSize, difficulty: String) {
super.init(size: size)
gameDifficulty = difficulty
timeStart = Date()
/*
*
* START: NEW CODE
*
*/
pauseMenuSprite = SKShapeNode(rectOf: size)
/*
*
* END: NEW CODE
*
*/
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func didMove(to view: SKView) {
backgroundColor = SKColor.white
print("Game starting with \(gameDifficulty) difficulty")
// Scale Sprites
sprite.setScale(0.3)
sprite2.setScale(0.3)
sprite.position = CGPoint(x: size.width/4,y: size.height/2)
sprite2.position = CGPoint(x: size.width/4 * 3,y: size.height/2)
/*
*
* START: NEW CODE
*
*/
gameNode.addChild(sprite)
gameNode.addChild(sprite2)
addChild(gameNode)
/*
*
* END: NEW CODE
*
*/
if gameDifficulty == "hard" {
let sprite3 = SKSpriteNode(imageNamed: "sprite")
sprite3.setScale(0.3)
sprite3.position = CGPoint(x: size.width/4 * 2,y: size.height/2)
addChild(sprite3)
}
pauseLabel.fontColor = SKColor.black
pauseLabel.position = CGPoint(x: size.width/4 * 2,y: size.height/4)
addChild(pauseLabel)
}
func touchDown(atPoint pos : CGPoint) {
}
func touchMoved(toPoint pos : CGPoint) {
}
func touchUp(atPoint pos : CGPoint) {
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches { self.touchDown(atPoint: t.location(in: self)) }
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches { self.touchMoved(toPoint: t.location(in: self)) }
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch = touches.first
let touchLocation = touch!.location(in: self)
let pausedTouchLocation = touch?.location(in: pauseMenuSprite)
if sprite.contains(touchLocation) {
print("You tapped the blue sprite")
/*
let alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.alert)
let action = UIAlertAction(title: "Ok", style: .default) { action in
// Handle when button is clicked
let reveal = SKTransition.doorsOpenVertical(withDuration: 0.5)
let menuScene = MenuScene(size: self.size)
self.view?.presentScene(menuScene, transition: reveal)
}
alert.addAction(action)
if let vc = self.scene?.view?.window?.rootViewController {
vc.present(alert, animated: true, completion: nil)
}
*/
}
if sprite2.contains(touchLocation) {
print("You tapped the purple sprite")
let now = Date()
let howLong = now.timeIntervalSinceReferenceDate - timeStart.timeIntervalSinceReferenceDate
let reveal = SKTransition.doorsOpenVertical(withDuration: 0.5)
let scoreScene = ScoreScene(size: self.size, score: howLong)
self.view?.presentScene(scoreScene, transition: reveal)
}
/*
*
* START: NEW CODE
*
*/
if pauseMenuContinueLabel.contains(pausedTouchLocation!) {
pauseMenuSprite.removeFromParent()
pauseMenuSprite.removeAllChildren()
gameNode.isPaused = true
}
if pauseMenuToMainMenuLabel.contains(pausedTouchLocation!) {
let reveal = SKTransition.doorsOpenVertical(withDuration: 0.5)
let menuScene = MenuScene(size: self.size)
self.view?.presentScene(menuScene, transition: reveal)
}
if pauseLabel.contains(touchLocation) {
print("pause")
setParametersForPauseMenu(size: size)
addChild(pauseMenuSprite)
gameNode.isPaused = true
}
/*
*
* END: NEW CODE
*
*/
}
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches { self.touchUp(atPoint: t.location(in: self)) }
}
override func update(_ currentTime: TimeInterval) {
// Called before each frame is rendered
}
/*
*
* START: NEW CODE
*
*/
func setParametersForPauseMenu(size: CGSize) {
pauseMenuSprite.fillColor = SKColor.white
pauseMenuSprite.alpha = 0.85
pauseMenuSprite.position = CGPoint(x: size.width / 2, y: size.height / 2)
pauseMenuSprite.zPosition = 100
pauseMenuTitleLabel.fontColor = SKColor.black
pauseMenuContinueLabel.fontColor = SKColor.black
pauseMenuToMainMenuLabel.fontColor = SKColor.black
pauseMenuTitleLabel.position = CGPoint(x: 0 ,y: size.height / 2 - pauseMenuSprite.frame.size.height / 6 )
pauseMenuContinueLabel.position = CGPoint(x: 0 ,y: size.height / 2 - pauseMenuSprite.frame.size.height / 6 * 4 )
pauseMenuToMainMenuLabel.position = CGPoint(x: 0 ,y: size.height / 2 - pauseMenuSprite.frame.size.height / 6 * 5)
pauseMenuSprite.addChild(pauseMenuTitleLabel)
pauseMenuSprite.addChild(pauseMenuContinueLabel)
pauseMenuSprite.addChild(pauseMenuToMainMenuLabel)
}
/*
*
* END: NEW CODE
*
*/
}
我在游戏场景中暂停游戏的问题纠结了一段时间。
正如其他几个人在评论中所建议的那样,构建一个 "pause scene" 来过渡到游戏暂停然后退出是一种有效的解决方案。这种方法避免了您可能 运行 在游戏暂停时在游戏场景中触发计时器或唤醒时跳过动画的问题。
为了实现暂停场景,我使用 UIViewController
的自定义子 class 来处理场景转换。
在我的 CustomViewController
内:
var sceneForGame: MyGameScene? //scene to handle gameplay
var paused: PauseScene? //scene to appear when paused
...
// presentPauseScene() and unpauseGame() handle the transition from game to pause and back
func presentPauseScene() {
//transition the outgoing scene
let transitionFadeLength = 0.30
let transitionFadeColor = UIColor.white
let pauseTransition = SKTransition.fade(with: transitionFadeColor, duration: transitionFadeLength)
pauseTransition.pausesOutgoingScene = true
let currentSKView = view as! SKView
currentSKView.presentScene(paused!, transition: pauseTransition)
}
func unpauseGame() {
let transitionFadeLength = 0.30
let transitionFadeColor = UIColor.white
let unpauseTransition = SKTransition.fade(with: transitionFadeColor, duration: transitionFadeLength)
unpauseTransition.pausesIncomingScene = false
let currentSKView = view as! SKView
currentSKView.presentScene(sceneForGame!, transition: unpauseTransition)
}
在 MyGameScene
class 内(SKScene
的子 class):
var parentViewController: CustomViewController? // ref to the managing view controller
...
// invoke this func when you want to pause
func setScenePause() {
parentViewController?.presentPauseScene()
self.isPaused = true
}
...
// you may need a snippet like this in your game scene's didMove(toView: ) to wake up when you come back to the game
else if self.isPaused {
self.isPaused = false
}
这是我的 PauseScene
实现。当用户点击暂停场景中的任何地方时,此版本将取消暂停,endGameButton
除外,它会终止当前游戏:
struct PauseNames {
static let endGameButton = "ENDGAME"
static let pausedButton = "PAUSE"
}
class PauseScene: SKScene {
var center : CGPoint?
var pauseButton: SKSpriteNode?
var endGameButton: SKSpriteNode?
var parentViewController: CustomViewController?
override func didMove(to view: SKView) {
setUpScene()
}
func setUpScene() {
self.backgroundColor = SKColor.white
self.center = CGPoint(x: self.size.width / 2, y: self.size.height / 2)
self.isUserInteractionEnabled = false
setUpSceneNodes()
showPauseEndButtons()
} // end setup scene
func setUpSceneNodes() {
let buttonScale: CGFloat = 0.5
let smallButtonScale: CGFloat = 0.25
let pauseOffset = //some CGPoint
let endGameOffset = //some CGPoint
pauseButton = SKSpriteNode(imageNamed: PauseNames.pausedButton)
pauseButton?.name = PauseNames.pausedButton
pauseButton?.anchorPoint = CGPoint(x: 0.5, y: 0.5)
pauseButton?.position = self.center! + pauseOffset
pauseButton?.alpha = 0
pauseButton?.setScale(buttonScale)
endGameButton = SKSpriteNode(imageNamed: PauseNames.endGameButton)
endGameButton?.name = PauseNames.pausedButton
endGameButton?.anchorPoint = CGPoint(x: 0.5, y: 0.5)
endGameButton?.position = self.center! + endGameOffset
endGameButton?.alpha = 0
endGameButton?.setScale(smallButtonScale)
}
func showPauseEndButtons() {
let buttonFadeInTime = 0.25
let pauseDelay = 1.0
self.addChild(pauseButton!)
self.addChild(endGameButton!)
pauseButton?.run(SKAction.fadeIn(withDuration: buttonFadeInTime))
endGameButton?.run(SKAction.fadeIn(withDuration: buttonFadeInTime))
self.run(SKAction.sequence([
SKAction.wait(forDuration: pauseDelay),
SKAction.run{ self.isUserInteractionEnabled = true }]))
}
func endGamePressed() {
// add confrim logic
parentViewController?.endGame()
}
func unpausePress() {
parentViewController?.unpauseGame()
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
let touchLocation = touch.location(in: self)
if endGameButton!.contains(touchLocation) {
endGamePressed()
return
}
else {
unpausePress()
}
} // end for each touch
} // end touchesBegan
override func update(_ currentTime: TimeInterval) {
/* Called before each frame is rendered */
}
} //end class PauseScene
(pauseButton
在这个版本中更多的是通知用户暂停状态的横幅)
上下文
虽然有些游戏选择放弃暂停菜单 - 推测是因为游戏持续时间短,例如 Don't Grind - 我个人认为暂停游戏是一项关键功能,我想学习如何在 SpriteKit 的 Swift 3 中实现它。
我曾看到有人尝试使用 UIAlertController
来做到这一点,但我——也许是错误的——认为更好的选择是在当前 SKView
.
我查看了 Apple 的 DemoBots,看看我是否能弄清楚他们是如何暂停游戏的。然而,在我的设备上下载并 运行 之后,它导致了错误,所以我不想效仿。但是,如果有人能彻底解释“LevelScene+Pause”、“SceneManager”、“SceneOperation”等众多文件以及它们如何协同工作,那也很酷。
问题
如何在 GameScene
上叠加 SKView
来制作暂停菜单?
最小工作示例
M.W.E., Whosebug SpriteKit with Menu,是一个准系统“游戏”,用于将答案语境化。请回答与 M.W.E.
有关的问题更新
以下是 M.W.E 的修改版本。文件“GameScene”。 它考虑了为要暂停的元素添加一个主节点和为暂停菜单添加另一个节点。
虽然暂停菜单有效,但背景仍然有效,即使 gameNode.isPaused = true
。 (尝试点击最左边的蓝色精灵)。
//
// GameScene.swift
// Whosebug
//
// Created by Sumner on 1/17/17.
// Copyright © 2017 Sumner. All rights reserved.
//
import SpriteKit
import GameplayKit
class GameScene: SKScene {
var cam: SKCameraNode!
var sprite = SKSpriteNode(imageNamed: "sprite")
var sprite2 = SKSpriteNode(imageNamed: "sprite2")
let pauseLabel = SKLabelNode(text: "Pause!")
/*
*
* START: NEW CODE
*
*/
let gameNode = SKNode()
var pauseMenuSprite: SKShapeNode!
let pauseMenuTitleLabel = SKLabelNode(text: "Pause Menu")
let pauseMenuContinueLabel = SKLabelNode(text: "Resume game?")
let pauseMenuToMainMenuLabel = SKLabelNode(text: "Main Menu?")
/*
*
* END: NEW CODE
*
*/
var timeStart: Date!
init(size: CGSize, difficulty: String) {
super.init(size: size)
gameDifficulty = difficulty
timeStart = Date()
/*
*
* START: NEW CODE
*
*/
pauseMenuSprite = SKShapeNode(rectOf: size)
/*
*
* END: NEW CODE
*
*/
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func didMove(to view: SKView) {
backgroundColor = SKColor.white
print("Game starting with \(gameDifficulty) difficulty")
// Scale Sprites
sprite.setScale(0.3)
sprite2.setScale(0.3)
sprite.position = CGPoint(x: size.width/4,y: size.height/2)
sprite2.position = CGPoint(x: size.width/4 * 3,y: size.height/2)
/*
*
* START: NEW CODE
*
*/
gameNode.addChild(sprite)
gameNode.addChild(sprite2)
addChild(gameNode)
/*
*
* END: NEW CODE
*
*/
if gameDifficulty == "hard" {
let sprite3 = SKSpriteNode(imageNamed: "sprite")
sprite3.setScale(0.3)
sprite3.position = CGPoint(x: size.width/4 * 2,y: size.height/2)
addChild(sprite3)
}
pauseLabel.fontColor = SKColor.black
pauseLabel.position = CGPoint(x: size.width/4 * 2,y: size.height/4)
addChild(pauseLabel)
}
func touchDown(atPoint pos : CGPoint) {
}
func touchMoved(toPoint pos : CGPoint) {
}
func touchUp(atPoint pos : CGPoint) {
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches { self.touchDown(atPoint: t.location(in: self)) }
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches { self.touchMoved(toPoint: t.location(in: self)) }
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch = touches.first
let touchLocation = touch!.location(in: self)
let pausedTouchLocation = touch?.location(in: pauseMenuSprite)
if sprite.contains(touchLocation) {
print("You tapped the blue sprite")
/*
let alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.alert)
let action = UIAlertAction(title: "Ok", style: .default) { action in
// Handle when button is clicked
let reveal = SKTransition.doorsOpenVertical(withDuration: 0.5)
let menuScene = MenuScene(size: self.size)
self.view?.presentScene(menuScene, transition: reveal)
}
alert.addAction(action)
if let vc = self.scene?.view?.window?.rootViewController {
vc.present(alert, animated: true, completion: nil)
}
*/
}
if sprite2.contains(touchLocation) {
print("You tapped the purple sprite")
let now = Date()
let howLong = now.timeIntervalSinceReferenceDate - timeStart.timeIntervalSinceReferenceDate
let reveal = SKTransition.doorsOpenVertical(withDuration: 0.5)
let scoreScene = ScoreScene(size: self.size, score: howLong)
self.view?.presentScene(scoreScene, transition: reveal)
}
/*
*
* START: NEW CODE
*
*/
if pauseMenuContinueLabel.contains(pausedTouchLocation!) {
pauseMenuSprite.removeFromParent()
pauseMenuSprite.removeAllChildren()
gameNode.isPaused = true
}
if pauseMenuToMainMenuLabel.contains(pausedTouchLocation!) {
let reveal = SKTransition.doorsOpenVertical(withDuration: 0.5)
let menuScene = MenuScene(size: self.size)
self.view?.presentScene(menuScene, transition: reveal)
}
if pauseLabel.contains(touchLocation) {
print("pause")
setParametersForPauseMenu(size: size)
addChild(pauseMenuSprite)
gameNode.isPaused = true
}
/*
*
* END: NEW CODE
*
*/
}
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches { self.touchUp(atPoint: t.location(in: self)) }
}
override func update(_ currentTime: TimeInterval) {
// Called before each frame is rendered
}
/*
*
* START: NEW CODE
*
*/
func setParametersForPauseMenu(size: CGSize) {
pauseMenuSprite.fillColor = SKColor.white
pauseMenuSprite.alpha = 0.85
pauseMenuSprite.position = CGPoint(x: size.width / 2, y: size.height / 2)
pauseMenuSprite.zPosition = 100
pauseMenuTitleLabel.fontColor = SKColor.black
pauseMenuContinueLabel.fontColor = SKColor.black
pauseMenuToMainMenuLabel.fontColor = SKColor.black
pauseMenuTitleLabel.position = CGPoint(x: 0 ,y: size.height / 2 - pauseMenuSprite.frame.size.height / 6 )
pauseMenuContinueLabel.position = CGPoint(x: 0 ,y: size.height / 2 - pauseMenuSprite.frame.size.height / 6 * 4 )
pauseMenuToMainMenuLabel.position = CGPoint(x: 0 ,y: size.height / 2 - pauseMenuSprite.frame.size.height / 6 * 5)
pauseMenuSprite.addChild(pauseMenuTitleLabel)
pauseMenuSprite.addChild(pauseMenuContinueLabel)
pauseMenuSprite.addChild(pauseMenuToMainMenuLabel)
}
/*
*
* END: NEW CODE
*
*/
}
我在游戏场景中暂停游戏的问题纠结了一段时间。
正如其他几个人在评论中所建议的那样,构建一个 "pause scene" 来过渡到游戏暂停然后退出是一种有效的解决方案。这种方法避免了您可能 运行 在游戏暂停时在游戏场景中触发计时器或唤醒时跳过动画的问题。
为了实现暂停场景,我使用 UIViewController
的自定义子 class 来处理场景转换。
在我的 CustomViewController
内:
var sceneForGame: MyGameScene? //scene to handle gameplay
var paused: PauseScene? //scene to appear when paused
...
// presentPauseScene() and unpauseGame() handle the transition from game to pause and back
func presentPauseScene() {
//transition the outgoing scene
let transitionFadeLength = 0.30
let transitionFadeColor = UIColor.white
let pauseTransition = SKTransition.fade(with: transitionFadeColor, duration: transitionFadeLength)
pauseTransition.pausesOutgoingScene = true
let currentSKView = view as! SKView
currentSKView.presentScene(paused!, transition: pauseTransition)
}
func unpauseGame() {
let transitionFadeLength = 0.30
let transitionFadeColor = UIColor.white
let unpauseTransition = SKTransition.fade(with: transitionFadeColor, duration: transitionFadeLength)
unpauseTransition.pausesIncomingScene = false
let currentSKView = view as! SKView
currentSKView.presentScene(sceneForGame!, transition: unpauseTransition)
}
在 MyGameScene
class 内(SKScene
的子 class):
var parentViewController: CustomViewController? // ref to the managing view controller
...
// invoke this func when you want to pause
func setScenePause() {
parentViewController?.presentPauseScene()
self.isPaused = true
}
...
// you may need a snippet like this in your game scene's didMove(toView: ) to wake up when you come back to the game
else if self.isPaused {
self.isPaused = false
}
这是我的 PauseScene
实现。当用户点击暂停场景中的任何地方时,此版本将取消暂停,endGameButton
除外,它会终止当前游戏:
struct PauseNames {
static let endGameButton = "ENDGAME"
static let pausedButton = "PAUSE"
}
class PauseScene: SKScene {
var center : CGPoint?
var pauseButton: SKSpriteNode?
var endGameButton: SKSpriteNode?
var parentViewController: CustomViewController?
override func didMove(to view: SKView) {
setUpScene()
}
func setUpScene() {
self.backgroundColor = SKColor.white
self.center = CGPoint(x: self.size.width / 2, y: self.size.height / 2)
self.isUserInteractionEnabled = false
setUpSceneNodes()
showPauseEndButtons()
} // end setup scene
func setUpSceneNodes() {
let buttonScale: CGFloat = 0.5
let smallButtonScale: CGFloat = 0.25
let pauseOffset = //some CGPoint
let endGameOffset = //some CGPoint
pauseButton = SKSpriteNode(imageNamed: PauseNames.pausedButton)
pauseButton?.name = PauseNames.pausedButton
pauseButton?.anchorPoint = CGPoint(x: 0.5, y: 0.5)
pauseButton?.position = self.center! + pauseOffset
pauseButton?.alpha = 0
pauseButton?.setScale(buttonScale)
endGameButton = SKSpriteNode(imageNamed: PauseNames.endGameButton)
endGameButton?.name = PauseNames.pausedButton
endGameButton?.anchorPoint = CGPoint(x: 0.5, y: 0.5)
endGameButton?.position = self.center! + endGameOffset
endGameButton?.alpha = 0
endGameButton?.setScale(smallButtonScale)
}
func showPauseEndButtons() {
let buttonFadeInTime = 0.25
let pauseDelay = 1.0
self.addChild(pauseButton!)
self.addChild(endGameButton!)
pauseButton?.run(SKAction.fadeIn(withDuration: buttonFadeInTime))
endGameButton?.run(SKAction.fadeIn(withDuration: buttonFadeInTime))
self.run(SKAction.sequence([
SKAction.wait(forDuration: pauseDelay),
SKAction.run{ self.isUserInteractionEnabled = true }]))
}
func endGamePressed() {
// add confrim logic
parentViewController?.endGame()
}
func unpausePress() {
parentViewController?.unpauseGame()
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
let touchLocation = touch.location(in: self)
if endGameButton!.contains(touchLocation) {
endGamePressed()
return
}
else {
unpausePress()
}
} // end for each touch
} // end touchesBegan
override func update(_ currentTime: TimeInterval) {
/* Called before each frame is rendered */
}
} //end class PauseScene
(pauseButton
在这个版本中更多的是通知用户暂停状态的横幅)