作者:手机用户2502873667 | 来源:互联网 | 2024-12-03 10:25
虽然SpriteKit框架已经具备了当应用进入非活动状态时自动暂停游戏的功能,但有时我们可能需要在应用恢复活跃状态时向用户显示一个‘点击恢复’的提示。当前,尽管我的游戏能够正确响应并暂停,但这个提示文字却没有显示出来。
为了实现这一功能,我在AppDelegate.swift
文件中添加了相应的通知处理器,用于在应用即将变为非活跃状态时发送暂停游戏的通知,并在应用恢复活跃状态时显示‘点击恢复’的提示。
AppDelegate.swift
func applicationWillResignActive(_ application: UIApplication) {
// 当应用即将从活跃状态变为非活跃状态时调用。这可能是由于临时中断(如来电或短信)或用户退出应用导致。
print("applicationWillResignActive")
NotificationCenter.default.post(name: Notification.Name("PauseGameScene"), object: nil)
NotificationCenter.default.post(name: Notification.Name("ShowPauseText"), object: nil)
}
GameScene.swift
class GameScene: SKScene, SKPhysicsContactDelegate {
private let tapToResume = SKLabelNode(fontNamed: "Noteworthy")
override func didMove(to view: SKView) {
NotificationCenter.default.addObserver(self, selector: #selector(pauseGameScene), name: Notification.Name("PauseGameScene"), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(showPauseText), name: Notification.Name("ShowPauseText"), object: nil)
tapToResume.text = "tap to resume"
tapToResume.position = CGPoint(x: frame.midX, y: frame.midY)
tapToResume.fOntSize= 55
tapToResume.isHidden = true
addChild(tapToResume)
}
@objc func pauseGameScene() {
print("Pausing game")
view?.isPaused = true
}
@objc func showPauseText() {
if view?.isPaused == true {
tapToResume.isHidden = false
print("Showing pause text")
}
}
override func touchesBegan(_ touches: Set, with event: UIEvent?) {
if isPaused {
view?.isPaused = false
if !tapToResume.isHidden {
tapToResume.isHidden = true
}
}
}
}
在尝试解决这个问题的过程中,我发现了一个有效的解决方案。通过将self.speed
和self.physicsWorld.speed
都设置为0.0,不仅可以暂停所有动作,还可以使物理世界停止更新。当应用再次激活时,只需将这两个属性重置为1.0即可恢复正常游戏状态。
改进后的GameScene.swift
class GameScene: SKScene, SKPhysicsContactDelegate {
private let tapToResume = SKLabelNode(fontNamed: "Noteworthy")
override func didMove(to view: SKView) {
NotificationCenter.default.addObserver(self, selector: #selector(pauseGameScene), name: Notification.Name("PauseGameScene"), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(showPauseText), name: Notification.Name("ShowPauseText"), object: nil)
}
@objc func pauseGameScene() {
physicsWorld.speed = 0.0
speed = 0.0
}
@objc func showPauseText() {
if physicsWorld.speed == 0.0 {
tapToResume.isHidden = false
}
}
override func touchesBegan(_ touches: Set, with event: UIEvent?) {
if physicsWorld.speed == 0.0 {
physicsWorld.speed = 1.0
speed = 1.0
if !tapToResume.isHidden {
tapToResume.isHidden = true
}
}
}
}
改进后的AppDelegate.swift
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func applicationWillResignActive(_ application: UIApplication) {
NotificationCenter.default.post(name: Notification.Name("PauseGameScene"), object: nil)
NotificationCenter.default.post(name: Notification.Name("ShowPauseText"), object: nil)
}
}