What does "didMove # to" mean for SKSpriteNode?

Of course, in the scene ...

class DotScene: SKScene {

    override func didMove(to view: SKView) {

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

you know that the scene is in place when called didMove#to.

(This is similar to ViewDidAppear, you could say.)

However

I do not know how to find out that a sprite has been added to the scene.

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 ...

There is simply - there must be - a call warning you that the node appeared on the scene successfully.

What is it?

+4
source share
1 answer

There is no way in SpriteKit to detect inside a custom sprite class when a node is added to the scene. This was ruled out because you have control when the sprite is added to the scene through addChildor moveToParent.

Spritekit MVC, UIKit. didMoveToView , - . . presentScene , , , . ( , , )

, , Key Value Observing (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, , , node ( KVO, , ), , , node , .

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))
}
+3

Source: https://habr.com/ru/post/1687946/


All Articles