So I made an SKSpriteNode like this:
SKSpriteNode *ball = [SKSpriteNode spriteNodeWithImageNamed:@"ball.png"];
ball.size = CGSizeMake(40, 40);
ball.position = CGPointMake(CGRectGetMidX(self.frame),CGRectGetMidY(self.frame));
ball.name = @"ball";
ball.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:20];
[self addChild:ball];
And I can move it around like this:
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInNode:self];
SKNode *node = [self nodeAtPoint:location];
if ([node.name isEqualToString:@"ball"]) {
draggedBall = [self nodeAtPoint:[[touches anyObject]locationInNode:self]];
draggedBallStartPosition = draggedBall.position;
}
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
if ([[touches anyObject]locationInNode:self].x -draggedBall.position.x < 50
&& [[touches anyObject]locationInNode:self].x -draggedBall.position.x > -50) {
draggedBall.position = [[touches anyObject]locationInNode:self];
draggedBall.physicsBody.affectedByGravity = NO;
}
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
float dx = draggedBall.position.x - draggedBallStartPosition.x;
float dy = draggedBall.position.y - draggedBallStartPosition.y;
NSLog(@"DX: %f DY: %f",dx,dy);
[draggedBall.physicsBody applyImpulse:CGVectorMake(dx, dy)];
draggedBall.physicsBody.affectedByGravity = YES;
draggedBall = nil;
}
draggedBall is an SKNode ivar. So what I want to do is swipe the ball and when it releases it continues to go in that direction. The quicker you swipe the greater the impulse. Now I tried (and failed) to do that, but this obviously doesn't work. Somehow the last direction of the ball needs to be detected, then the amount of time between starting to go in that direction and releasing the ball. And depending on how long that amount of time is, affect the velocity of the ball. Since this is a game-mechanic that is frequently used, I figure that there is an standardized way of doing this. Anyway, thanks for helping.