タップした位置に、人形が集合するようなiPhoneアプリのサンプルを描いてみます。
使った画像
動かすとこんな感じです
サンプルコード
#import “ViewController.h”
#import <SpriteKit/SpriteKit.h>
@interface TogetherScene : SKScene
@property BOOL contentCreated;
@property (nonatomic, strong) NSValue *selectedPoint;
@property (nonatomic, strong) NSMutableArray *origin;
@end
@implementation TogetherScene
– (void)didMoveToView:(SKView *)view
{
if (!self.contentCreated) {
[self createSceneContents];
self.contentCreated = YES;
}
}
– (void)createSceneContents
{
self.physicsWorld.gravity = CGVectorMake(0, 0);
self.origin = [NSMutableArray array];
NSArray *imageNames = @[@”red”,@”blue”,@”yellow”,@”green”];
for (int i=0; i<12; i++) {
float angle = 2.0 * (M_PI / 12.0) * i;
float x = 100 * cos(angle) + CGRectGetMidX(self.frame);
float y = 100 * sin(angle) + CGRectGetMidY(self.frame);
SKSpriteNode *one = [SKSpriteNode spriteNodeWithImageNamed:imageNames[i%4]];
one.name = @”menber”;
one.position = CGPointMake(x, y);
one.zRotation = angle + M_PI / 2.0;
[self addChild:one];
one.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:10];
[self.origin addObject:[NSValue valueWithCGPoint:one.position]];
}
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
CGPoint p = [[touches anyObject] locationInNode:self];
self.selectedPoint = [NSValue valueWithCGPoint:p];
}
– (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
self.selectedPoint = nil;
__block int count = 0;
[self enumerateChildNodesWithName:@”menber” usingBlock:^(SKNode *node, BOOL *stop) {
SKAction *back = [SKAction moveTo:[self.origin[count] CGPointValue] duration:0.1];
[node runAction:back];
count++;
}];
}
– (void)update:(NSTimeInterval)currentTime
{
[self enumerateChildNodesWithName:@”menber” usingBlock:^(SKNode *node, BOOL *stop) {
if (self.selectedPoint) {
CGPoint p = [self.selectedPoint CGPointValue];
float dx = p.x – node.position.x;
float dy = p.y – node.position.y;
CGVector mygravity = CGVectorMake(dx / 100.0, dy / 100.0);
[node.physicsBody applyForce:mygravity];
}
}];
}
@end
@interface ViewController ()
@end
@implementation ViewController
– (void)viewDidAppear:(BOOL)animated
{
SKView *spriteView = [[SKView alloc] initWithFrame:self.view.bounds];
[self.view addSubview:spriteView];
SKScene *scene = [[TogetherScene alloc] initWithSize:spriteView.frame.size];
[spriteView presentScene:scene];
}
@end