Passing integer between scenes, iphone game sprite-kit

蓝咒 提交于 2020-01-24 00:57:16

问题


I have a scene where the user chooses level in a game, then i want to switch to a game scene with the level the user chose. I want to create the game scene with the right level but to do this i need to pass an integer which is the level-number to the game scene so i know which level to load.

My question is, how do i accomplish this? I have looked at the userdata property of nodes but could not figure out how to use it to accomplish what i want. Any help would be deeply appreciated.


回答1:


When you call [self.view presentScene:scene transition:transition] inside of your level selection scene, first set up your new scene with the level number. SO:

//GameScene.h
//This is the public interface for your game scene
@import SpriteKit;
@interface GameScene : SKScene
@property (nonatomic, assing)NSInteger levelNumber;
@end

And then

//Level Selection Scen
//Select.m
#import "GameScene.h"
... Rest of your code
User selects level and you prepare for transition and call
- (void)transitionToLevel:(NSInteger)level{
    GameScene *destinationScene = [[GameScene alloc] initWithSize:self.size];
    destinationScene.levelNumber = level;
    SKTransition *transition = //Set up transition here
    [self.view presentScene:destinationScene transition:transition];
}    

And in your game scene's implementation

//GameScene.m
#import "GameScene.h"
@implementation GameScene
-(id)initWithSize:(CGSize){
    if (self.levelNumber == 1){
        [self playLevelOne]; //Where this is where you play your game
    }
    else if (self.levelNumber == 2){
        [self playLevelTwo];
    }
}
- (void)playLevelOne{
    //Level Implementation
}
- (void)playLevelTwo{
    //Level Implementation
}
@end

You would do this for each level you plan to support




回答2:


    // First Scene
    NSUserDefaults.standardUserDefaults().setInteger(12345, forKey:"SCORE")

    // Second Scene
    if let myScore: AnyObject = NSUserDefaults.standardUserDefaults().objectForKey("SCORE") {
        println(myScore)
        finalScore = myScore as IntegerLiteralType
    }


来源:https://stackoverflow.com/questions/21817840/passing-integer-between-scenes-iphone-game-sprite-kit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!