我在Swift中使用SpriteKit制作游戏,但在显示广告时遇到了麻烦。当播放器死亡时,广告会显示,但是当我关闭它时,它不会停留在当前场景(GameScene)中,而是出于某种原因切换到MainMenu场景。实际上,如果你仔细观察,你可以看到"游戏结束了#34;出现文本,当广告向上滑动显示时,它会切换到MainMenu场景。我看到帖子here并尝试了答案所说的内容(将所有内容从ViewWillLayoutSubviews移动到ViewDidLoad等)并且它没有用。有任何想法吗?感谢。
以下是GameViewController中涉及广告的所有代码:
class GameViewController: UIViewController, UIAlertViewDelegate, GADInterstitialDelegate {
var musicPlayer = AVAudioPlayer()
var musicUrl = Bundle.main.url(forResource: "Loops2.mp3", withExtension: nil)
var interstitial: GADInterstitial!
override func viewDidLoad() {
super.viewDidLoad()
interstitial = loadAd()
NotificationCenter.default.addObserver(self, selector: #selector(self.playerDied), name: NSNotification.Name("ShowAd"), object: nil)
NotificationCenter.default.post(name: NSNotification.Name("ShowingAd"), object: nil)
super.viewWillLayoutSubviews()
let skView = self.view as! SKView
skView.ignoresSiblingOrder = true
skView.showsFPS = true
skView.showsNodeCount = true
let mainMenu = MainMenu()
mainMenu.scaleMode = .aspectFill
mainMenu.size = view.bounds.size
skView.presentScene(mainMenu)
}
func playerDied() {
if self.interstitial.isReady {
self.interstitial.present(fromRootViewController: self)
}
}
func loadAd() -> GADInterstitial {
let interstitial = GADInterstitial(adUnitID: "ca-app-pub-3940256099942544/1033173712")
interstitial.delegate = self
interstitial.load(GADRequest())
return interstitial
}
func interstitialDidDismissScreen(_ ad: GADInterstitial) {
NotificationCenter.default.post(name: NSNotification.Name("AdDismissed"), object: nil)
interstitial = loadAd()
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
if let url = musicUrl {
try! musicPlayer = AVAudioPlayer(contentsOf: url)
musicPlayer.numberOfLoops = -1
musicPlayer.prepareToPlay()
musicPlayer.play()
}
}
我使用NotificationCenter向GameViewController发出信号,告知何时展示广告。我不认为需要来自GameScene的代码,但如果你认为它会有所帮助,那就问问吧。谢谢!