I have a game where circular objects shoot up from the bottom of the screen and I would like to be able to swipe them to flick them in the direction of my swipe. My issue is, I don't know how to calculate the vector/direction of the swipe in order to get the circular object to get flicked in the proper direction with the proper velocity.
The static vector "(5,5)" I am using needs to be calculated by the swipe speed and direction of the swipe. Also, I need to make sure that once I make first contact with the object, it no longer happens, as to refrain from double hitting the object. Here's what I am doing currently:
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
for (UITouch *touch in touches) {
CGPoint location = [touch locationInNode:self];
SKNode* node = [self nodeAtPoint:location];
[node.physicsBody applyImpulse:CGVectorMake(5, 5) atPoint:location];
}
}
In
touchesBegan
save the touch location as a CGPoint you can access throughout your app.In
touchesEnded
calculate the distance and direction of your initial touch (touchesBegan) and ending touch (touchesEnded). Then apply the appropriate Impulse.To refrain from double hitting, add a bool canHit that you set to NO when the impulse is applied and set back to YES when you are ready to hit again. Before applying the impulse, make sure canHit is set to YES.
Here's an example of how to detect a swipe gesture:
First, define instance variables to store the starting location and time .
In touchesBegan, save the location/time of a touch event.
Define parameters of the swipe gesture. Adjust these accordingly.
In touchesEnded, determine if the user's gesture was a swipe by comparing the differences between starting and ending locations and time stamps.
There is another way to do it, you can add a pan gesture and then get the velocity from it:
First add pan gesture in your view:
Then handle the gesture: