简体   繁体   中英

Organizing zPosition values in Sprite Kit with enums

We have been using enums to organize the zPositions of our sprites. As we started to add SKNodes with several subsprites to our game, the structure quickly began to break down. Some child sprites that were placed on the screen had to have negative values in order to be beneath other nodes with children. These negative values are hard to keep track of in relation to other sprites in separate enums.

Is there a better way to organize the zPosition of sprites (especially those with sub-sprites) than using enums?

Upon reading more into your issue, it looks like you are using multiple enums to organize your z order. I suggest using a single enum for the z - ordering of your game.

Use layers to organize your scene:

- (instancetype)initWithSize:(CGSize)size {
    if (self = [super initWithSize:size]) {
        self.view.ignoresSiblingOrder = YES;        
        [self addLayers];
    }
    return self;
}

- (void)addLayers {
    self.backgroundLayer = [SKNode node];
    self.backgroundLayer.zPosition = 100;
    [self addChild:self.backgroundLayer];

    self.playerLayer = [SKNode node];
    self.playerLayer.zPosition = 300;
    [self addChild:self.playerLayer];

    self.enemyLayer = [SKNode node];
    self.enemyLayer.zPosition = 400;
    [self addChild:self.enemyLayer];

    // UI elements must be on top of all nodes on the scene
    self.uiLayer = [SKNode node];
    self.uiLayer.zPosition = 1000;
}

- (void)addBackgrounds {
    SKSpriteNode *backgroundNode1 = [SKSpriteNode spriteNodeWithTexture:[self backgroundTexture1]];
    backgroundNode1.zPosition = 10;
    [self.backgroundLayer addChild:backgroundNode1];

    SKSpriteNode *backgroundNode2 = [SKSpriteNode spriteNodeWithTexture:[self backgroundTexture2]];
    backgroundNode2.zPosition = 20;
    [self.backgroundLayer addChild:backgroundNode2];
}    
.... etc

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM