I'm looking at this drag and drop tutorial by Ray Wenderleich, it allows sprites to be dragged on the screen, however, there's no gravity and the sprites are left pinned in place once the user lifts the finger.
At the same time I'm looking at this SpriteKit collision demo by Apple, it has collisions between objects.
Then there's this tutorial which shows how to apply impulse to sprites.
I've combined the demos together, so my scene has gravity, edge collision and bouncing, but the drag and drop code still does not have inertia.
How can I modify drag and drop behavior into "drag and flick" for sprites? I'm looking for a behavior similar to a view within a scrollview - acceleration, deceleration and inertia.
The code below has two modes - flick which applies impulse onto a sprite and drag which changes the sprite's location. I'm not sure how to combine the two code paths to
- (void)handlePanFrom:(UIPanGestureRecognizer *)recognizer {
CGPoint touchLocation = [recognizer locationInView:recognizer.view];
touchLocation = [self convertPointFromView:touchLocation];
if (recognizer.state == UIGestureRecognizerStateBegan) {
[self selectNodeForTouch:touchLocation];
} else if (recognizer.state == UIGestureRecognizerStateChanged) {
SKNode* node = [self selectNodeForTouch:touchLocation];
//this is the flick gesture - pings the
double angle = atan2(touchLocation.y-node.position.y,touchLocation.x-node.position.x);
[node.physicsBody applyImpulse:CGVectorMake(20*cos(angle), 20*sin(angle))];
//CGPoint translation = [recognizer translationInView:recognizer.view];
// translation = CGPointMake(translation.x, -translation.y);
// [self panForTranslation:translation];
// [recognizer setTranslation:CGPointZero inView:recognizer.view];
} else if (recognizer.state == UIGestureRecognizerStateEnded) {
}
}
Here's the drag and drop code:
- (void)panForTranslation:(CGPoint)translation {
CGPoint position = [_selectedNode position];
if([[_selectedNode name] isEqualToString:kAnimalNodeName]) {
[_selectedNode setPosition:CGPointMake(position.x + translation.x, position.y + translation.y)];
} else {
CGPoint newPos = CGPointMake(position.x + translation.x, position.y + translation.y);
[_background setPosition:[self boundLayerPos:newPos]];
}
}