iPhone おしゃべり

文字を入力すると四角がおしゃべりしながらとんでいくというiPhoneアプリのサンプルコードを描いてみます。

動かすとこんな感じです

サンプルコード

#import “ViewController.h”

#import <SpriteKit/SpriteKit.h>

@interface TalkScene : SKScene

– (void)talk:(NSString*)string;

@end

@implementation TalkScene

– (void)didMoveToView:(SKView *)view

{

    [self createSceneContents];

}

– (void)createSceneContents

{

    self.physicsWorld.gravity = CGVectorMake(0, –0.05);

    [self createWall];

    [self createFace];

}

– (void)createWall

{

    self.physicsBody = [SKPhysicsBody bodyWithEdgeLoopFromRect:CGRectMake(0, 0, CGRectGetMaxX(self.frame), CGRectGetMaxY(self.frame) – 60)];

}

– (void)createFace

{

    SKSpriteNode *face = [SKSpriteNode spriteNodeWithColor:[SKColor yellowColor] size:CGSizeMake(50, 50)];

    face.name = @”face”;

    face.position = CGPointMake(160, 160);

    [self addChild:face];

    face.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:face.frame.size];

    face.physicsBody.restitution = 1.0;

    

    for (int i=0; i<2; i++) {

        SKSpriteNode *eye = [SKSpriteNode spriteNodeWithColor:[SKColor blackColor] size:CGSizeMake(5, 5)];

        eye.position = CGPointMake(i * 2510, 0);

        [face addChild:eye];

    }

    

    SKSpriteNode *m = [SKSpriteNode spriteNodeWithColor:[SKColor blackColor] size:CGSizeMake(15, 2)];

    m.position = CGPointMake(2, –15);

    [face addChild:m];

}

– (void)talk:(NSString *)string

{

    SKNode *face = [self childNodeWithName:@”face”];

    [face.physicsBody applyImpulse:CGVectorMake(30, 20)];

    

    for (int i=0; i<string.length; i++) {

        NSString *w = [string substringWithRange:NSMakeRange(i, 1)];

        [self performSelector:@selector(showWord:) withObject:w afterDelay:0.06 * i];

    }

}

– (void)showWord:(NSString *)s

{

    NSLog(@”%@”, s);

    SKNode *face = [self childNodeWithName:@”face”];

    SKLabelNode *l = [SKLabelNode node];

    l.text = s;

    l.position = face.position;

    [self addChild:l];

}

@end

@interface ViewController () <UITextFieldDelegate>

@property (nonatomic, weak) TalkScene *talkScene;

@end

@implementation ViewController

– (void)viewDidAppear:(BOOL)animated

{

    SKView *spriteVeiw = [[SKView alloc] initWithFrame:self.view.bounds];

    [self.view addSubview:spriteVeiw];

    

    TalkScene *scene = [[TalkScene alloc] initWithSize:spriteVeiw.frame.size];

    [spriteVeiw presentScene:scene];

    self.talkScene = scene;

    

    UITextField *t = [[UITextField alloc] initWithFrame:CGRectMake(10, 20, 400, 30)];

    t.borderStyle = UITextBorderStyleRoundedRect;

    [self.view addSubview:t];

    t.delegate = self;

}

– (BOOL)textFieldShouldReturn:(UITextField *)textField {

    [textField resignFirstResponder];

    

    [self.talkScene performSelector:@selector(talk:) withObject:textField.text afterDelay:0.5];

    return NO;

}

@end