[英]How do I create a pause and unpause button in Swift and Sprite Kit?
我有以下代码。 程序运行时,单击左上角的暂停按钮将暂停游戏,但中间的未暂停按钮不会显示。 似乎程序正在运行命令以暂停游戏,然后再运行命令以创建取消暂停按钮,但是我不知道该如何解决。
import SpriteKit
import GameplayKit
class GameScene: SKScene, SKPhysicsContactDelegate {
var lanecounter:CGFloat = 0
var lastOpen:CGFloat = 0
var score:Int = 0
var BGspeed:CGFloat = -700
var player:SKSpriteNode?
let scoreLabel = SKLabelNode()
let highScoreLabel = SKLabelNode()
var direction:Int?
let noCategory:UInt32 = 0
let carCategory:UInt32 = 0b1
let playerCategory:UInt32 = 0b1 << 1
let pointCategory:UInt32 = 0b1 << 2
let bumperCategory:UInt32 = 0b1 << 3
var died:Bool?
var pause:Bool = false
var gameStarted:Bool?
var restartBTN = SKSpriteNode()
var pauseBTN = SKSpriteNode()
var unpauseBTN = SKSpriteNode()
func createPauseBTN()
{
pauseBTN = SKSpriteNode(color: SKColor.purple, size: CGSize(width: 100, height: 100))
pauseBTN.position = CGPoint(x: -self.frame.width/2 + 20, y: self.frame.height/2 - 20)
pauseBTN.zPosition = 10
self.addChild(pauseBTN)
}
func createunPauseBTN()
{
unpauseBTN = SKSpriteNode(color: SKColor.purple, size: CGSize(width: 100, height: 100))
unpauseBTN.position = CGPoint(x: 0, y: 0)
unpauseBTN.zPosition = 1000
self.addChild(unpauseBTN)
//pauseGame()
//scene?.view?.isPaused = true
}
func pauseGame() {
scene?.view?.isPaused = true
createunPauseBTN()
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches
{
let location = touch.location(in: self)
if died == true
{
if restartBTN.contains(location) {
restartScene()
}
}
if pauseBTN.contains(location) {
print(pause)
createunPauseBTN()
print("asd")
pauseBTN.removeFromParent()
pauseGame()
}
if unpauseBTN.contains(location) {
scene?.view?.isPaused = false
createPauseBTN()
}
}
}
您的问题是您正在暂停SKView,它将暂停所有操作。
scene?.view?.isPaused = true
这意味着您的SKScene中的所有内容(例如SKActions,addingChildren等)都将无法工作/停止工作,除非您再次将其设置为false。
通常最好创建一个worldNode并将需要暂停的所有节点添加到该节点。 苹果公司也在DemoBots中做到这一点。
因此,在您的课程中添加另一个属性
let worldNode = SKNode()
并将其添加到DidMoveToView
的场景
addChild(worldNode)
比将您需要暂停的所有其他节点(例如玩家,敌人等)添加到此worldNode
worldNode.addChild(someNode1)
worldNode.addChild(someNode2)
比起您的暂停代码,您应该这样说
worldNode.isPaused = true
physicsWorld.speed = 0
在简历代码中
worldNode.isPaused = false
physicsWorld.speed = 1
这应该给您更多的灵活性,因为您仍然可以做一些事情,例如让某些SKAction运行(例如针对您的背景)。 它还应该使您的暂停动作更流畅。
希望这可以帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.