iOS7 Sprite Kit 學習


iOS 7有一個新功能 Sprite Kit 這個有點類似cocos2d 感覺用法都差不多。下面簡單來介紹下Sprite Kit 

About Sprite Kit

Sprite Kit provides a graphics rendering and animation infrastructure that you can use to animate arbitrary textured images, or sprites. Sprite Kit uses a traditional rendering loop that allows processing on the contents of each frame before it is rendered. Your game determines the contents of the scene and how those contents change in each frame. Sprite Kit does the work to render frames of animation efficiently using the graphics hardware. Sprite Kit is optimized to allow essentially arbitrary changes to each frame of animation.

Sprite Kit also provides other functionality that is useful for games, including basic sound playback support and physics simulation. In addition, Xcode provides built-in support for Sprite Kit, allowing complex special effects and texture atlases to be easily created and then used in your app. This combination of framework and tools makes Sprite Kit a good choice for games and other apps that require similar kinds of animation. For other kinds of user-interface animation, use Core Animation instead.

../Art/update_loop_2x.png

 

可以參考官方文檔。:https://developer.apple.com/library/prerelease/ios/documentation/GraphicsAnimation/Conceptual/SpriteKit_PG/Introduction/Introduction.html#//apple_ref/doc/uid/TP40013043-CH1-SW1 

Jumping into Sprite Kit

The best way to learn Sprite Kit is to see it in action. This example creates a pair of scenes and animates content in each. By working through this example, you will learn some of the fundamental techniques for working with Sprite Kit content, including:

  • Using scenes in a Sprite Kit–based game.

  • Organizing node trees to draw content.

  • Using actions to animate scene content.

  • Adding interactivity to a scene.

  • Transitioning between scenes.

  • Simulating physics inside a scene.

Getting Started

Xcode5.0以上。。

首先新建一個項目 SpriteWalkthrough 。 

項目建好后在 ViewController.m 里添加如下代碼

打開storyboard 然后找到右邊 Sustom Slass 把Class 改成SKView!!!這個一定要改,不然會報錯 -[UIView setShowsFPS:]: unrecognized selector sent to instance 0x9742e30

#import <SpriteKit/SpriteKit.h>

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    SKView *spriteView = (SKView*)self.view;
    
    spriteView.showsFPS = YES;
    spriteView.showsDrawCount = YES;
    spriteView.showsNodeCount = YES;
    // Do any additional setup after loading the view, typically from a nib.
}

新建一個class  命名為HelloScene.h文件不需要做修改

#import <SpriteKit/SpriteKit.h>

@interface HelloScene : SKScene

@end

 

然后再回到ViewController.m .修改如下

#import "HelloScene.h"
-(void)viewWillAppear:(BOOL)animated
{
     
    HelloScene* hello = [[HelloScene alloc] initWithSize:CGSizeMake(self.view.frame.size.width,self.view.frame.size.height)];
    SKView *spriteView = (SKView*)self.view;
    [spriteView presentScene:hello];
    
}

OK 。。run it ..

 

2.然后在HelloScene.m里添加如下

@interface HelloScene()
@property BOOL contentCreated;
@end

 

-(void)didMoveToView:(SKView *)view
{
    if(!self.contentCreated)
    {
        [self  createSceneContents];
        self.contentCreated = YES;
    }
}

-(void)createSceneContents
{
    NSLog(@"createSceneContents");
    self.backgroundColor = [SKColor blackColor];
    self.scaleMode = SKSceneScaleModeAspectFit;
    [self addChild:[self newHelloNode]];
}

 

-(SKLabelNode*)newHelloNode
{
    SKLabelNode *helloNode = [SKLabelNode labelNodeWithFontNamed:@"Chalkduster"];
    helloNode.name = @"helloNode";//@ 這個和下面的一樣
    helloNode.text = @"hello game ";
    helloNode.fontSize = 24;
    helloNode.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame));
    return helloNode;
}

 

這個時候可以運行一次。

 

接下來繼續,在HelloScene.m 里添加

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    
    SKNode *helloNode = [self childNodeWithName:@"helloNode"]; //@與上面的相同
    if(helloNode !=nil)
    {
       
        helloNode.name = nil;
        SKAction *moveUp = [SKAction moveByX:0 y:100.0 duration:0.5]; //向上移動
        SKAction *zoom = [SKAction scaleTo:2.0 duration:0.25];    //擴大兩倍
        SKAction *pause = [SKAction waitForDuration:0.5];    //暫停
        SKAction *fadeAway = [SKAction fadeOutWithDuration:0.25];  //消失
        SKAction *remove = [SKAction removeFromParent];
        SKAction *moveSequence = [SKAction sequence:@[moveUp, zoom, pause, fadeAway, remove]];
        [helloNode runAction:moveSequence];
        
    }
}

 

再編譯運行

 

 

新建一個class 命名為 SpaceshipScene 然后在SpaceshipScene.m里添加如下 

@import "SpaceshipScene.h"

@interface SpaceshipScene ()
@property BOOL contentCreated;
@end

@implementation SpaceshipScene
- (void)didMoveToView:(SKView *)view
{
    if (!self.contentCreated)
    {
        [self createSceneContents];
        self.contentCreated = YES;
    }
}

- (void)createSceneContents
{
    self.backgroundColor = [SKColor blackColor];
    self.scaleMode = SKSceneScaleModeAspectFit;
}
@end

.h 

#import <SpriteKit/SpriteKit.h>

@interface SpaceshipScene : SKScene

@end

 

然后回到

SpaceshipScene.m 修改如下代碼。

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    
    SKNode *helloNode = [self childNodeWithName:@"helloNode"]; //@與上面的相同
    if(helloNode !=nil)
    {
       
        helloNode.name = nil;
        SKAction *moveUp = [SKAction moveByX:0 y:100.0 duration:0.5]; //向上移動
        SKAction *zoom = [SKAction scaleTo:2.0 duration:0.25];    //擴大兩倍
        SKAction *pause = [SKAction waitForDuration:0.5];    //暫停
        SKAction *fadeAway = [SKAction fadeOutWithDuration:0.25];  //消失
        SKAction *remove = [SKAction removeFromParent];
        SKAction *moveSequence = [SKAction sequence:@[moveUp, zoom, pause, fadeAway, remove]];
        //[helloNode runAction:moveSequence];
        [helloNode runAction: moveSequence completion:^{
            SKScene *spaceshipScene  = [[SpaceshipScene alloc] initWithSize:self.size];
            SKTransition *doors = [SKTransition doorsOpenVerticalWithDuration:0.5];
            [self.view presentScene:spaceshipScene transition:doors];
        }];
    }
}

運行。。

 

最后把SpaceshipScene.m 文件修改如下

//
//  SpaceshipScene.m
//  SpriteWalkthrough
//
//  Created by qingyun on 8/13/13.
//  Copyright (c) 2013 qingyun. All rights reserved.
//

#import "SpaceshipScene.h"

@interface SpaceshipScene ()
@property BOOL contentCreated;
@end

@implementation SpaceshipScene


- (void)didMoveToView:(SKView *)view
{
    if (!self.contentCreated)
    {
        [self createSceneContents];
        self.contentCreated = YES;
    }
}

- (void)createSceneContents
{
    self.backgroundColor = [SKColor blackColor];
    self.scaleMode = SKSceneScaleModeAspectFit;
    
    SKSpriteNode *spaceship = [self newSpaceship];
    spaceship.position = CGPointMake(CGRectGetMidX(self.frame),CGRectGetMidY(self.frame)-150);
    [self addChild:spaceship];
    
    //@3
    SKAction *makeRocks = [SKAction sequence: @[
                                                [SKAction performSelector:@selector(addRock) onTarget:self],
                                                [SKAction waitForDuration:0.10 withRange:0.15]
                                                ]];
    [self runAction: [SKAction repeatActionForever:makeRocks]];
}


- (SKSpriteNode *)newSpaceship
{
    SKSpriteNode *hull = [[SKSpriteNode alloc] initWithColor:[SKColor grayColor] size:CGSizeMake(64,32)];
    
    SKAction *hover = [SKAction sequence:@[
                                           [SKAction waitForDuration:1.0],
                                           [SKAction moveByX:100 y:50.0 duration:1.0],
                                           [SKAction waitForDuration:1.0],
                                           [SKAction moveByX:-100.0 y:-50 duration:1.0]]];
    [hull runAction: [SKAction repeatActionForever:hover]]; //重復移動hover 里的action 
    
    //@2
    SKSpriteNode *light1 = [self newLight];
    light1.position = CGPointMake(-28.0, 6.0);
    [hull addChild:light1];
    
    SKSpriteNode *light2 = [self newLight];
    light2.position = CGPointMake(28.0, 6.0);
    [hull addChild:light2];
    
    //@3
    hull.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:hull.size];
    hull.physicsBody.dynamic = NO;
    
    return hull;
}

//@2
- (SKSpriteNode *)newLight
{
    SKSpriteNode *light = [[SKSpriteNode alloc] initWithColor:[SKColor yellowColor] size:CGSizeMake(8,8)];
    
    SKAction *blink = [SKAction sequence:@[
                                           [SKAction fadeOutWithDuration:0.25],
                                           [SKAction fadeInWithDuration:0.25]]];
    SKAction *blinkForever = [SKAction repeatActionForever:blink];  //重復閃閃發光。
    [light runAction: blinkForever];
    
    return light;
}

//@3
static inline CGFloat skRandf() {
    return rand() / (CGFloat) RAND_MAX;
}
static inline CGFloat skRand(CGFloat low, CGFloat high) {
    return skRandf() * (high - low) + low;
}

- (void)addRock
{
    SKSpriteNode *rock = [[SKSpriteNode alloc] initWithColor:[SKColor brownColor] size:CGSizeMake(8,8)];
    rock.position = CGPointMake(skRand(0, self.size.width), self.size.height-50);
    rock.name = @"rock";
    rock.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:rock.size];
    rock.physicsBody.usesPreciseCollisionDetection = YES;
    [self addChild:rock];
}

-(void)didSimulatePhysics
{
    [self enumerateChildNodesWithName:@"rock" usingBlock:^(SKNode *node, BOOL *stop) {
        if (node.position.y < 0)
            [node removeFromParent];
    }];
}

@end
 

好了。一個簡單的sprite 小游戲做成了。

 

demo 下載地址: https://github.com/qingjoin/SpriteKit


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM