使用NSCoding保存和加载Background对象状态

时间:2013-11-08 14:35:36

标签: cocos2d-iphone nscoding

在我的代码中,我在ScrollingBackground中创建了BackgroundLayer的实例,而BackgroundLayer也在GameScene中创建了一个实例。我想保存ScrollingBackground状态,所以当玩家死亡时我可以保持不变。以下是相关代码:

ScrollingBackground.m:

-(id)initWithBackgroundLayer: (BackgroundLayer *)layer{
if (self = [super init]) {
    backgroundRepeatCount =0;
    scrollSpeed = 0.0; 
    backgroundCount = 0;
    backgroundArray = [[NSMutableArray alloc] init]


bg = [CCSprite spriteWithSpriteFrameName:@"bg1.png"];
bg.position = ccp(s.width/2, s.height/2);
[currentBatchNode addChild:bg];

bgSwap = [CCSprite spriteWithSpriteFrameName:@"bg2.png"];
bgSwap.position = ccp(s.width/2, 3*s.height/2 -1.0);
[currentBatchNode addChild: bgSwap];

                .
                . 
                .
   }
}

-(void) encodeWithCoder:(NSCoder *)aCoder {

[aCoder encodeObject:self.bg forKey:@"bg"];
[aCoder encodeObject:self.bgSwap forKey:@"bgSwap"];
[aCoder encodeObject:self.displayedBg forKey:@"displayedBg"];
[aCoder encodeObject:self.backgroundArray forKey:@"backgroundArray"];
[aCoder encodeObject:self.currentBatchNode forKey:@"currentBatchNode"];    
        .
        .
        .
}

-(id) initWithCoder:(NSCoder *) aDecoder {

 self = [super init];
 if(self != nil) {

    self.bg = [aDecoder decodeObjectForKey:@"bg"];
    self.bgSwap = [aDecoder decodeObjectForKey:@"bgSwap"];
    self.displayedBg = [aDecoder decodeObjectForKey:@"displayedBg"];
    self.backgroundArray = [aDecoder decodeObjectForKey:@"backgroundArray"];
    self.currentBatchNode = [aDecoder decodeObjectForKey:@"currentBatchNode"];
              .
              . 
              .
   }
}

编辑:

  1. 如何保存上述状态?

  2. 如何重新加载?

  3. 这是保存CCSprites和CCSpriteBatchNodes的正确方法吗?

0 个答案:

没有答案