iPhone文字ドロップ

入力した文字を画面上からポトポトと落とすiPhoneアプリのサンプルコードを描いてみます。

#import “ViewController.h”

#import <SpriteKit/SpriteKit.h>

@interface WordScene : SKScene <UITextFieldDelegate>

@end

@implementation WordScene

– (void)didMoveToView:(SKView *)view

{

    self.physicsBody = [SKPhysicsBody bodyWithEdgeLoopFromRect:CGRectMake(0, 200, 320, 400)];

}

– (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string

{

    UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:CGPointZero radius:30 startAngle:0 endAngle:2.0*M_PI clockwise:NO];

    SKShapeNode *node = [SKShapeNode node];

    node.path = path.CGPath;

    node.position = CGPointMake((range.location % 5) * 60 + 30, CGRectGetMaxY(self.frame));

    [self addChild:node];

    

    node.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:30];

    

    SKLabelNode *l = [SKLabelNode node];

    l.text = string;

    l.verticalAlignmentMode = SKLabelVerticalAlignmentModeCenter;

    [node addChild:l];

    

    return YES;

}

@end

@interface ViewController ()

@end

@implementation ViewController

– (void)viewDidLoad

{

    [super viewDidLoad];

    

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

    [self.view addSubview:sv];

    WordScene *scene = [[WordScene alloc] initWithSize:sv.frame.size];

    [sv presentScene:scene];

    

    UITextField *field = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 200, 30)];

    field.center = CGPointMake(160, 50);

    field.borderStyle = UITextBorderStyleRoundedRect;

    field.layer.cornerRadius = 5;

    field.layer.borderWidth = 1.0f;

    field.layer.borderColor = [[UIColor grayColor] CGColor];

    field.autocapitalizationType = UITextAutocapitalizationTypeAllCharacters;

    [self.view addSubview:field];

    

    field.delegate = scene;

}

– (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

}

@end