SpriteKit如何创建和切换到不同场景

3

我用Sprite Kit创建了一个游戏,但是当游戏启动时,它直接进入游戏。如何实现不同的场景,比如主菜单和游戏结束场景,并通过在屏幕上按标签或在游戏过程中进行接触来实现它们之间的过渡。


你可以在你的视图控制器中简单地呈现一个启动场景。从启动屏幕,你可以呈现游戏场景。 - 0x141E
1个回答

14

你可以尝试像这样做。创建一个新的类,随便取个名字(我取名为GameStartMenu),并将其设置为SKScene的子类。

在你的ViewController .m文件中,用新的类名替换MyScene:

// Create and configure the scene.
SKScene * scene = [GameStartMenu sceneWithSize:skView.bounds.size];
scene.scaleMode = SKSceneScaleModeAspectFill;

那么在你的新类`.m`中输入以下内容:

#import "GameStartMenu.h"
#import "MyScene.h"

@implementation GameStartMenu

-(id)initWithSize:(CGSize)size {
    if (self = [super initWithSize:size]) {
        /* Setup your scene here */

        self.backgroundColor = [SKColor colorWithRed:1.5 green:1.0 blue:0.5 alpha:0.0];

        NSString *nextSceneButton;
        nextSceneButton = @"Start";

        SKLabelNode *myLabel = [SKLabelNode labelNodeWithFontNamed:@"Chalkduster"];

        myLabel.text = nextSceneButton;
        myLabel.fontSize = 30;
        myLabel.fontColor = [SKColor blackColor];
        myLabel.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame));
        myLabel.name = @"scene button";

        [self addChild:myLabel];

    }
    return self;
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    /* Called when a touch begins */

    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInNode:self];
    SKNode *node = [self nodeAtPoint:location];

    if ([node.name isEqualToString:@"scene button"]) {

        SKTransition *reveal = [SKTransition fadeWithDuration:3];

        MyScene *scene = [MyScene sceneWithSize:self.view.bounds.size];
        scene.scaleMode = SKSceneScaleModeAspectFill;
        [self.view presentScene:scene transition:reveal];
    }
}

@end

这将创建一个标签,当触摸时转换到新场景(MyScene)。删除您需要的任何内容,例如背景颜色等。现在我也是编程新手,所以这可能完全是错误的方法,但是到目前为止,这对我有效。


上一个关于sktransition的回答非常好,我一直在寻找这个。 - Septronic

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接