SpriteKit .sks文件和子类

时间:2014-12-17 05:52:23

标签: objective-c sprite-kit

Apple在他们的WWDC 2014 Session 608视频中演示了此代码,该视频介绍了SpriteKit的最佳实践。

AppDelegate.m

+ (instancetype)unarchiveFromFile:(NSString *)file {
    /* Retrieve scene file path from the application bundle */
    NSString *nodePath = [[NSBundle mainBundle] pathForResource:file ofType:@"sks"];
    /* Unarchive the file to an SKScene object */
    NSData *data = [NSData dataWithContentsOfFile:nodePath
                                      options:NSDataReadingMappedIfSafe
                                        error:nil];
    NSKeyedUnarchiver *arch = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
    [arch setClass:self forClassName:@"SKScene"];
    SKScene *scene = [arch decodeObjectForKey:NSKeyedArchiveRootObjectKey];
    [arch finishDecoding];

    return scene;
}

我理解它正在做的事情的要点,但我感到困惑的是如何将此代码用于任何其他.sks文件。我尝试从我的GameScene.m类中调用unarchiveFromFile方法,但无济于事。我在这个主题上阅读了帖子here,但它没有澄清事情。

修改 根据Okapi的建议,我在GameScene.m类的新OS X SceneKit项目中尝试了以下内容:

#import "GameScene.h"

@implementation GameScene

-(void)didMoveToView:(SKView *)view {
    SKNode *nodeInScene2 = [self childNodeWithName:@"object1"];
    for (SKNode *blah in [SKScene unarchiveFromFile:@"Scene2"].children) {
        [nodeInScene2 addChild:blah];
    }
}

-(void)update:(CFTimeInterval)currentTime {
    /* Called before each frame is rendered */
}

@end

我有2个.sks文件。第一个叫做GameScene.sks,在那里有一个名为“object1”的精灵。我想添加存储在“Scene2.sks”中的子项。 didMoveToView方法中的循环给了我一个错误。我究竟做错了什么?这就是Apple在他们的WWDC 608视频中所做的,但也许我错过了一些东西,因为我无法在线找到他们的项目。

2 个答案:

答案 0 :(得分:1)

+unarchiveFromFile:被定义为GameViewController.m中SKScene上的一个类别。如果要在其他地方使用它,则需要复制该代码。

@implementation SKScene (Unarchive)

+ (instancetype)unarchiveFromFile:(NSString *)file {
    /* Retrieve scene file path from the application bundle */
    NSString *nodePath = [[NSBundle mainBundle] pathForResource:file ofType:@"sks"];
    /* Unarchive the file to an SKScene object */
    NSData *data = [NSData dataWithContentsOfFile:nodePath
                                          options:NSDataReadingMappedIfSafe
                                            error:nil];
    NSKeyedUnarchiver *arch = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
    [arch setClass:self forClassName:@"SKScene"];
    SKScene *scene = [arch decodeObjectForKey:NSKeyedArchiveRootObjectKey];
    [arch finishDecoding];

    return scene;
}

@end

答案 1 :(得分:0)

这个人也把我挂了一会儿。我最终在每个需要它的子类中声明了unarchiveFromFile,然后在我想要转换场景时调用它。像这样......

if (contactQuery == (playerCategory | proceedCategory)) {
    SKScene *levelTwo = [LevelTwo unarchiveFromFile:@"LevelTwo"];
    [self.view presentScene:levelTwo transition:[SKTransition doorsCloseHorizontalWithDuration:0.5]];
}

可以下载完整的示例代码here