精灵套件

时间:2015-08-21 19:28:46

标签: ios objective-c ipad sprite-kit skspritenode

我在此代码中设置背景颜色:

- (void)randomBackground {
    int random = arc4random() % 3;
    NSLog(@"%d", random);
    switch (random) {
        case 0:
            self.background = [SKSpriteNode spriteNodeWithImageNamed:@"image1"];
            break;
        case 1:
            self.background = [SKSpriteNode spriteNodeWithImageNamed:@"image2"];

            break;
        case 2:
            self.background = [SKSpriteNode spriteNodeWithImageNamed:@"image3"];
            break;

    }
        self.background.position = CGPointMake(self.size.width / 2.0, self.size.height / 2.0);
}

-(id)initWithSize:(CGSize)size {
    if (self = [super initWithSize:size]) {
        NSLog(@"Size: %@", NSStringFromCGSize(size));

    }
    self.physicsWorld.gravity = CGVectorMake(0, 0);
    self.physicsWorld.contactDelegate = self;
    return self;
}

-(void)didMoveToView:(nonnull SKView *)view {
        self.backgroundColor = [SKColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1.0];
        [self randomBackground];
        self.player = [SKSpriteNode spriteNodeWithImageNamed:@"ninja"];
        self.player.position = CGPointMake(self.player.size.width / 2.0, self.player.size.height / 2.0);
        [self removeAllChildren];

        [self addChild:self.background];
        [self addChild:self.player];
}

在我的播放器丢失后,我呈现另一个场景,然后再次呈现这个场景:

SKAction *loseAction = [SKAction runBlock:^{
    SKTransition *reveal = [SKTransition flipHorizontalWithDuration:0.5];
    GameOverScene *gameOverScene = [[GameOverScene alloc] initWithSize:self.size won:NO];
    [self.view presentScene:gameOverScene transition:reveal];

}];
[hero runAction:[SKAction sequence:@[move, loseAction, moveDone]]];

以下是我再次呈现主场景的方式:

[self runAction:
 [SKAction sequence:@[[SKAction waitForDuration:0.5],
                      [SKAction runBlock:^{
     [self.parentScene removeAllChildren];
     SKTransition *reveal = [SKTransition flipHorizontalWithDuration:0.5];
     GameScene *myScene = [GameScene sceneWithSize:self.size];
     [self.view presentScene:myScene transition:reveal];
 }]
                      ]]];

问题在于,有时候,当加载特定背景时,整个内容似乎都被它覆盖,但是,当我对场景的子项进行nslog时,背景位于数组的第一位。 结果,我只能看到背景。奇怪的是,这只发生在某些背景上,而在其他背景上则没问题,内容也能正常显示。

任何想法如何解决?

1 个答案:

答案 0 :(得分:1)

初始化的顺序实际上非常有趣,但它是一个完全不同的主题。要解决您的问题,您需要通过属性zPosition在z轴上指定每个节点的位置。例如,如果你写:

background.zPosition = -1;
myNode.zPosition = 1;

myNode将始终位于background之上。