我在swift 4上编写的spritekit应用程序中遇到了场景转换问题
我有一个gameover.swift文件声明EndScene类:
import Foundation
import SpriteKit
class EndScene: SKScene, SKPhysicsContactDelegate {
var RestartButton : UIButton!
var HighScore : Int!
var HighScoreLabel : UILabel!
var GameOverLabel : UILabel!
override func didMove(to view: SKView) {
self.scene?.backgroundColor = SKColor.white
RestartButton = UIButton(frame: CGRect(x:0, y:0, width: view.frame.size.width/3
, height: 30))
RestartButton.titleLabel?.adjustsFontSizeToFitWidth = true
RestartButton.center = CGPoint(x: view.frame.size.width/2 , y: view.frame.size.height/1.5)
RestartButton.setTitle("restart", for: UIControlState.normal)
RestartButton.showsTouchWhenHighlighted = true
RestartButton.setTitleColor(SKColor.black, for: UIControlState.normal)
RestartButton.addTarget(self, action: #selector(EndScene.Restart), for: UIControlEvents.touchUpInside)
self.view?.addSubview(RestartButton)
GameOverLabel = UILabel (frame: CGRect(x:0, y:0, width: view.frame.size.width/3.8, height: 30))
GameOverLabel.center = CGPoint(x: view.frame.size.width/2 , y: view.frame.size.height/10)
GameOverLabel.textColor = SKColor.red
GameOverLabel.text = "Game Over"
self.view?.addSubview(GameOverLabel)
}
func Restart(){
RestartButton.removeFromSuperview()
GameOverLabel.removeFromSuperview()
self.removeAllChildren()
self.view?.presentScene(GameScene(), transition: SKTransition.reveal(with: .up, duration: 0.3))
}
}
GameScene是GameScene.swift文件中声明的类。它包含描述游戏过程的类声明。
问题是:
当游戏从GameScene开始时,它工作正常(所有对象都被淹没,物理工作)但是当我从EndScene重新启动游戏时它工作不正确(1个物体不时被淹死但是其他所有物体都没有被淹死,甚至背景颜色没有被淹死)。
一般来说可以用它吗?
答案 0 :(得分:2)
您不应该通过调用其无参数初始化程序来创建GameScene
。查看生成的GameScene
文件中GameViewController.swift
的显示方式。您会看到它调用(fileNamed:)
初始化程序。
所以改变这一行:
self.view?.presentScene(GameScene(), transition: SKTransition.reveal(with: .up, duration: 0.3))
要
self.view?.presentScene(GameScene(fileNamed: "GameScene"), transition: SKTransition.reveal(with: .up, duration: 0.3))