`
prevention
  • 浏览: 70787 次
社区版块
存档分类
最新评论

iOS Dev (49) 苹果官方 SpriteKit Game 模版

阅读更多

iOS Dev (49) 苹果官方 SpriteKit Game 模版

基本架构

- AppDelegate - ViewController:基础的 VC。 - MyScene:动画场景,处理动作等等。

在 AppDelegate 中实例化一个 ViewController,在 ViewController 中实例化一个 MyScene。

AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.rootViewController = [[ViewController alloc] init];   
    [self.window makeKeyAndVisible];
    return YES;
}

ViewController

- (void)loadView
{
    self.view = [[SKView alloc] initWithFrame:CGRectMake(0, 0, 320, 568)];
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    SKView * skView = (SKView *)self.view;
    SKScene * scene = [MyScene sceneWithSize:skView.bounds.size];
    scene.scaleMode = SKSceneScaleModeAspectFill;

    [skView presentScene:scene];
}

上面这个很好看懂。loadView 里面初始化 view,这个一定要记住,不能在 init 中做,也不能在 viewDidLoad 中做。

viewDidLoad 中,先实例化一个 MyScene,设置这个 MyScene 带 scaleMode 为 SKSceneScaleModeAspectFill。最后再在 view 上 present 这个 scene。

以上步骤,都是常规做法。

MyScene

-(id)initWithSize:(CGSize)size {    
    if (self = [super initWithSize:size]) {
        self.backgroundColor = [SKColor colorWithRed:0.15 green:0.15 blue:0.3 alpha:1.0];

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

        myLabel.text = @"Hello, World!";
        myLabel.fontSize = 30;
        myLabel.position = CGPointMake(CGRectGetMidX(self.frame),
                                       CGRectGetMidY(self.frame));

        [self addChild:myLabel];
    }
    return self;
}

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

    for (UITouch *touch in touches) {
        CGPoint location = [touch locationInNode:self];

        SKSpriteNode *sprite = [SKSpriteNode spriteNodeWithImageNamed:@"Spaceship"];

        sprite.position = location;

        SKAction *action = [SKAction rotateByAngle:M_PI duration:1];

        [sprite runAction:[SKAction repeatActionForever:action]];

        [self addChild:sprite];

        NSLog(@"for loop");
    }

    NSLog(@"touchesBegan");
}

实现 touchesBegan 方法,这个方法是 MyScene 从 UIResponder 继承来的,其定义为:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;

这个继承关系是这样带:

MyScene -> SKScene -> SKEffectNode -> SKNode -> UIResponder

回头来说这个 touchesBegan 吧。

  1. 先获取到 touch 的点 location。
  2. 创建一个 sprite,用的是 spriteNodeWithImageNamed 这个 API。
  3. 设置这个 sprite 带位置。
  4. 创立一个 SKAction,让 sprite 来 repeat 这个 action。
  5. 最后呢,把这个 sprite 加到 scene 上吧。

转载请注明来自大锐哥的博客:http://prevention.iteye.com

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics