落とし穴に落とさないようにボールを坂に転がすiPhoneアプリのサンプルコードを描いてみます。
#import “ViewController.h”
@import SpriteKit;
@interface ViewController ()
@property (nonatomic, weak) SKScene *scene;
@end
@implementation ViewController
– (void)viewDidLoad {
[super viewDidLoad];
[self setupScene];
[self createMountHole];
}
– (void)setupScene {
SKView *sv = [[SKView alloc] initWithFrame:self.view.bounds];
SKScene *s = [SKScene sceneWithSize:sv.frame.size];
s.backgroundColor = [UIColor brownColor];
[sv presentScene:s];
[self.view addSubview:sv];
self.scene = s;
}
– (void)createMountHole {
SKShapeNode *top = [SKShapeNode shapeNodeWithRectOfSize:CGSizeMake(100, 10)];
top.fillColor = [UIColor greenColor];
top.position = CGPointMake(70, CGRectGetMaxY(self.view.bounds) – 50);
top.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:CGSizeMake(100, 10)];
top.physicsBody.dynamic = NO;
[self.scene addChild:top];
float l = CGRectGetMaxX(self.view.bounds) – 100;
float angle = 30.0 * M_PI / 180.0;
SKShapeNode *slopeA = [SKShapeNode shapeNodeWithRectOfSize:CGSizeMake(2.0/5.0 * l / cos(angle), 10) cornerRadius:0];
slopeA.position = CGPointMake(4.0/5.0 * l + 100, (1.0/5.0 * l) * tan(angle));
slopeA.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:CGSizeMake(2.0/5.0 * l / cos(angle), 10)];
slopeA.physicsBody.dynamic = NO;
SKShapeNode *slopeB = [SKShapeNode shapeNodeWithRectOfSize:CGSizeMake(2.0/5.0 * l / cos(angle), 10) cornerRadius:0];
slopeB.position = CGPointMake(1.0/5.0 * l + 100, (4.0/5.0 * l) * tan(angle));
slopeB.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:CGSizeMake(2.0/5.0 * l / cos(angle), 10)];
slopeB.physicsBody.dynamic = NO;
SKShapeNode *hole = [SKShapeNode shapeNodeWithRectOfSize:CGSizeMake(1.0/5.0 * l / cos(angle), 10) cornerRadius:0];
hole.position = CGPointMake(2.5/5.0 * l + 100, (2.5/5.0 * l) * tan(angle));
hole.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:CGSizeMake(1.0/5.0 * l / cos(angle), 10)];
hole.physicsBody.dynamic = NO;
for (SKShapeNode *node in @[slopeA, slopeB, hole]) {
node.fillColor = top.fillColor;
node.zRotation = -angle;
[self.scene addChild:node];
}
[hole runAction:[SKAction repeatActionForever:[SKAction sequence:@[[SKAction moveByX:0 y:-80 duration:1.5], [SKAction moveByX:0 y:80 duration:1.5]]]]];
}
– (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
SKShapeNode *ball = [SKShapeNode shapeNodeWithCircleOfRadius:10];
ball.position = CGPointMake(0, CGRectGetMaxY(self.view.bounds));
ball.lineWidth = 3;
[self.scene addChild:ball];
ball.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:10];
[ball.physicsBody applyImpulse:CGVectorMake(5, 0)];
}
@end