Here is an example of how to detect gestures:
Define instance variables first to preserve the starting location and time.
CGPoint start; NSTimeInterval startTime;
In touchsBegan, save the location / time of the touch event.
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { if ([touches count] > 1) { return; } UITouch *touch = [touches anyObject]; CGPoint location = [touch locationInNode:self];
Define swipe gestures. Adjust them accordingly.
#define kMinDistance 25 #define kMinDuration 0.1 #define kMinSpeed 100 #define kMaxSpeed 500
In touchs.Ended, determine if the user's gesture was successful by comparing the differences between start and end locations and timestamps.
- (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { UITouch *touch = [touches anyObject]; CGPoint location = [touch locationInNode:self]; // Determine distance from the starting point CGFloat dx = location.x - start.x; CGFloat dy = location.y - start.y; CGFloat magnitude = sqrt(dx*dx+dy*dy); if (magnitude >= kMinDistance) { // Determine time difference from start of the gesture CGFloat dt = touch.timestamp - startTime; if (dt > kMinDuration) { // Determine gesture speed in points/sec CGFloat speed = magnitude / dt; if (speed >= kMinSpeed && speed <= kMaxSpeed) { // Calculate normalized direction of the swipe dx = dx / magnitude; dy = dy / magnitude; NSLog(@"Swipe detected with speed = %g and direction (%g, %g)",speed, dx, dy); } } } }
source share