我正在尝试学习SpriteKit。我想在代码中为场景添加一个矩形/正方形;但该项目从未显示;
我想做的就是在屏幕上添加一个白色方块,但发现它永远不会添加。
在断点中,我注意到似乎永远不会调用didMove()。
我做错了什么?
class GameScene: SKScene {
override func didMove(to view: SKView) {
let item = SKSpriteNode(color: .white, size: CGSize(width: 150, height: 200))
item.position = CGPoint(x: self.size.width/2, y: self.size.height/2)
self.addChild(item)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
}
override func update(_ currentTime: TimeInterval) {
// Called before each frame is rendered
}
}
更新
我没有更改xcode生成的视图控制器
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if let view = self.view as! SKView? {
// Load the SKScene from 'GameScene.sks'
if let scene = SKScene(fileNamed: "GameScene") {
// Set the scale mode to scale to fit the window
scene.scaleMode = .aspectFill
// Present the scene
view.presentScene(scene)
}
view.ignoresSiblingOrder = true
view.showsFPS = true
view.showsNodeCount = true
}
}
override var shouldAutorotate: Bool {
return true
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
if UIDevice.current.userInterfaceIdiom == .phone {
return .allButUpsideDown
} else {
return .all
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
override var prefersStatusBarHidden: Bool {
return true
}
}
没有GameScene.sks,我删除了这个文件,因为我不想使用sks文件
答案 0 :(得分:1)
如果从未达到didMove(查看:)中的断点,那么您的ViewController肯定不会出于某种原因呈现该场景。你可以打开你的ViewController文件(例如GameViewController.swift),看看你是否有任何这些行(或任何相应的效果):
let viewSize = UIScreen.main.bounds.size
let scene = GameScene(size: viewSize)
let skView = self.view as! SKView
skView.presentScene(scene)
答案 1 :(得分:0)
结果视图控制器没有呈现场景并将其更改为此,按照@Stoyan发布的代码工作,我看到我的精灵显示
覆盖func viewDidLoad(){ super.viewDidLoad()
if let view = self.view as! SKView? {
let viewSize = UIScreen.main.bounds.size
let scene = GameScene(size: viewSize)
view.ignoresSiblingOrder = true
view.showsFPS = true
view.showsNodeCount = true
view.presentScene(scene)
}