sprite Kit的奇怪行为
Posted
技术标签:
【中文标题】sprite Kit的奇怪行为【英文标题】:Strange behavior of sprite Kit 【发布时间】:2015-08-21 19:28:46 【问题描述】:我在这段代码中设置背景颜色:
- (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】:初始化的顺序其实很有意思,不过是完全不同的话题。要解决您的问题,您需要通过属性zPosition
指定每个节点在 z 轴上的位置。例如,如果你写:
background.zPosition = -1;
myNode.zPosition = 1;
myNode
将始终显示在background
之上。
【讨论】:
以上是关于sprite Kit的奇怪行为的主要内容,如果未能解决你的问题,请参考以下文章
SKView bounds.size 在触摸事件时反转(Sprite Kit)