如何从另一个 .swift 文件添加精灵?
How to add a sprite from another .swift file?
我有一个项目我已经做了一段时间了。我正在使用 Sprite-Kit 但现在希望能够从不同于 GameScene.swift 文件的 swift 文件添加子节点。
此处显示了加载 GameScene 的视图控制器的一些主要代码:
let skView:SKView = SKView()
let theScene:SKScene = SKScene()
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if let theScene = GameScene.unarchiveFromFile("GameScene") as? GameScene {
// Configure the view.
let skView = self.view as! SKView
skView.showsFPS = true
skView.showsNodeCount = true
/* Sprite Kit applies additional optimizations to improve rendering performance */
skView.ignoresSiblingOrder = true
/* Set the scale mode to scale to fit the window */
theScene.scaleMode = .ResizeFill //.AspectFill
var customSceneSize = CGSizeMake(2560, 1600)
theScene.size = customSceneSize
skView.presentScene(theScene)
makeFakeStuff() // prepares some sample data
}
}
通常我使用 "self.addChild" 在 GameScene.swift 文件中添加精灵。这对另一个 .swift 文件不起作用,所以我试过了:
theScene.addChild(flyingCell)
我试过了:
skView.scene?.addChild(flyingCell)
这些执行没有错误,但屏幕上没有任何显示。当我尝试以其他方式使用相同的精灵代码并将其放入 GameScene.swift 文件并使用 "self.addChild" 时,它会绘制它,因此精灵代码(未显示)看起来很好(位置、zPosition 等)。我还制作了 "flyingCell" 一个全局变量,看看是否有帮助……没有。有什么想法吗?
我的代码有两处错误。
第一个在我的问题中可见:我应该使用 "var" 而不是 "let"
声明 "theScene"
第二个问题是我的游戏场景,我需要把"theScene = self"
Apple DTS 帮我解决了这个问题。
我有一个项目我已经做了一段时间了。我正在使用 Sprite-Kit 但现在希望能够从不同于 GameScene.swift 文件的 swift 文件添加子节点。
此处显示了加载 GameScene 的视图控制器的一些主要代码:
let skView:SKView = SKView()
let theScene:SKScene = SKScene()
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if let theScene = GameScene.unarchiveFromFile("GameScene") as? GameScene {
// Configure the view.
let skView = self.view as! SKView
skView.showsFPS = true
skView.showsNodeCount = true
/* Sprite Kit applies additional optimizations to improve rendering performance */
skView.ignoresSiblingOrder = true
/* Set the scale mode to scale to fit the window */
theScene.scaleMode = .ResizeFill //.AspectFill
var customSceneSize = CGSizeMake(2560, 1600)
theScene.size = customSceneSize
skView.presentScene(theScene)
makeFakeStuff() // prepares some sample data
}
}
通常我使用 "self.addChild" 在 GameScene.swift 文件中添加精灵。这对另一个 .swift 文件不起作用,所以我试过了:
theScene.addChild(flyingCell)
我试过了:
skView.scene?.addChild(flyingCell)
这些执行没有错误,但屏幕上没有任何显示。当我尝试以其他方式使用相同的精灵代码并将其放入 GameScene.swift 文件并使用 "self.addChild" 时,它会绘制它,因此精灵代码(未显示)看起来很好(位置、zPosition 等)。我还制作了 "flyingCell" 一个全局变量,看看是否有帮助……没有。有什么想法吗?
我的代码有两处错误。
第一个在我的问题中可见:我应该使用 "var" 而不是 "let"
声明 "theScene"第二个问题是我的游戏场景,我需要把"theScene = self"
Apple DTS 帮我解决了这个问题。