SKSpriteNode, added to/removed from parent hook

后端 未结 2 1608
耶瑟儿~
耶瑟儿~ 2021-01-13 06:18

Is there any (best practice) way within the class to hook the events when a SKSpriteNode (or SKNode) is added onto and removed from a parent node?

2条回答
  •  走了就别回头了
    2021-01-13 06:58

    Without the need of Kobold Kit, you can sub-class a SKSpriteNode (or any SKNode for the fact) and extend the removeFromParent function that SKNodes own.

    For example:

    FLSprite.m:

    #import "FLSprite.h"
    
    @implementation FLSprite
    
    -(void)removeFromParent {
        [super removeFromParent];
        NSLog(@"I print when I'm Removed");
        //here's where you'll add your hooking functions
    }
    
    @end
    

    MyScene.m:

    -(id)initWithSize:(CGSize)size {    
        if (self = [super initWithSize:size]) {
        FLSprite* sprite = [FLSprite spriteNodeWithColor:[UIColor blackColor] size:CGSizeMake(200, 100)];
            [sprite setPosition:CGPointMake(100.0, 50.0)];
            [self addChild:sprite];
            [sprite removeFromParent];
    
        }
        return self;
    }
    

    As for adding a child, since you add a child as such (in most cases) [self addChild:node]; you'll need to extend the addChild in the view you are adding to. For example you'll add the following to your MyScene.m, since we are adding the sprite to that view

    -(void)addChild:(SKNode *)node {
        [super addChild:node];
        NSLog(@"added child");
    }
    

    This is pretty much what Steffen Itterheim did to acheive this functions, as he explained in his posting.

提交回复
热议问题