カフェウォール錯視

今日はカフェウォール錯視を表示するiPhoneアプリのサンプルコードを描いてみます。

#import “ViewController.h”

@import SpriteKit;

@interface CafeScene : SKScene

@end

@implementation CafeScene

– (void)didMoveToView:(SKView *)view

{

    self.backgroundColor = [SKColor whiteColor];

    [self createCafeWall];

}

– (void)createCafeWall

{

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

        SKSpriteNode *slope = [SKSpriteNode spriteNodeWithColor:[SKColor lightGrayColor] size:CGSizeMake(300, 2)];

        slope.position = CGPointMake(160, i * 40 + 60);

        [self addChild:slope];

        slope.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:slope.size];

        slope.physicsBody.dynamic = NO;

        

        for (int j=0; j<5; j++) {

            SKSpriteNode *box = [SKSpriteNode spriteNodeWithColor:[SKColor blackColor] size:CGSizeMake(40, 40)];

            box.position = CGPointMake(j * 80 + (i%2) * 20 + 10, slope.position.y + 20);

            [self addChild:box];

        }

    }

}

– (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

{

    CGPoint p = [[touches anyObject] locationInNode:self];

    

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

    SKShapeNode *ball = [SKShapeNode node];

    ball.path = path.CGPath;

    ball.position = CGPointMake(-20, p.y);

    ball.fillColor = [SKColor yellowColor];

    [self addChild:ball];

    

    ball.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:10];

    [ball.physicsBody applyImpulse:CGVectorMake(5, 0)];

}

– (void)didSimulatePhysics

{

    [self enumerateChildNodesWithName:@”ball” usingBlock:^(SKNode *ball, BOOL *stop) {

        if (ball.position.x > 330 || ball.position.x < –10) {

            [ball removeFromParent];

        }

    }];

}

@end

@interface ViewController ()

@end

@implementation ViewController

– (void)viewDidLoad

{

    [super viewDidLoad];

    

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

    [self.view addSubview:spriteView];

    SKScene *scene = [[CafeScene alloc] initWithSize:spriteView.frame.size];

    [spriteView presentScene:scene];

}

@end