什么是SKMriteNode的“didMove#to”?

时间:2017-10-21 15:56:04

标签: sprite-kit skspritenode

当然,在一个场景......

class DotScene: SKScene {

    override func didMove(to view: SKView) {

        print("this scene is now in place...")

你知道在调用didMove#to时场景已经存在。

(就像ViewDidAppear,你可以说。)

然而

我不知道如何知道 sprite 已添加到场景中。

class Spaceship: SKSpriteNode {

    func wtf() {

        this sprite has just been added to a scene
        (such as with .childNode)
        this sprite is now in place in the scene ...

只需 - 必须是 - 一个提醒您节点已成功出现在场景上的呼叫。

这是什么?

1 个答案:

答案 0 :(得分:3)

在SpriteKit中,当节点添加到场景时,无法检测自定义sprite类的内部。由于您可以通过addChildmoveToParent将精灵添加到场景中,因此可以省略此操作。

Spritekit不符合MVC架构,就像UIKit那样。 didMoveToView存在的原因之一是因为View的目的只是输出显示。控制器负责处理View后面的代码。现在视图控制器可用于从视图中调用presentScene,但如果我们正在转换,我们实际上不知道场景正式附加到视图的哪个位置。 (除此之外还有其他原因,我只举一个例子)

现在要解决这个问题,您可以实现键值观察(KVO),并在scene设置时收听。要做到这一点,只需:

override init()
{
    super.init()
    addObserver(self, forKeyPath: #keyPath(SKNode.scene), options: [.old, .new, .initial], context: nil)
}

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) 
{
    if keyPath == #keyPath(SKNode.scene) && self.scene != nil 
    {
        didAttachToScene()
    }
}

func didAttachToScene()
{
}

deinit 
{
    removeObserver(self, forKeyPath: #keyPath(SKNode.scene))
}

现在,我还没有对此进行测试,我目前处于Windows环境中,但是如果这不起作用,您可以在节点连接到父节点时进行监听(我实际上已经使用KVO,所以我知道它是可能的),并推断我们是否在这样的场景,因为一个节点必须有一个父级甚至有资格在场景上。

override init()
{
    super.init()
    addObserver(self, forKeyPath: #keyPath(SKNode.parent), options: [.old, .new, .initial], context: nil)
}

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) 
{
    if keyPath == #keyPath(SKNode.parent) && self.scene != nil 
    {
        didAttachToScene()
    }
}

func didAttachToScene()
{
}

deinit 
{
    removeObserver(self, forKeyPath: #keyPath(self.parent))
}