Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swiping in Coco2d

I am trying to get the swiping to work for Cocos2d latest version here is my code:

-(void) setupGestureRecognizers 
{
    UISwipeGestureRecognizer *swipeLeft = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeLeft)];

    [swipeLeft setDirection:UISwipeGestureRecognizerDirectionLeft];

    [swipeLeft setNumberOfTouchesRequired:1];

    [[[CCDirector sharedDirector] openGLView] addGestureRecognizer:swipeLeft];


}

It does not detect the swipe at all!

UPDATE 1:

I updated the code to the following and still no swipes are detected.

-(void) setupGestureRecognizers 
{
    UISwipeGestureRecognizer *swipeLeft = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeLeft)];

    [swipeLeft setDirection:UISwipeGestureRecognizerDirectionLeft];

    [swipeLeft setNumberOfTouchesRequired:1];

    [[[[CCDirector sharedDirector] openGLView] window] setUserInteractionEnabled:YES];

    [[[CCDirector sharedDirector] openGLView] setUserInteractionEnabled:YES];
    [[[CCDirector sharedDirector] openGLView] addGestureRecognizer:swipeLeft];


}
like image 239
azamsharp Avatar asked Feb 02 '12 13:02

azamsharp


1 Answers

I've tried to make this work as well but I've found an easier and also better to control method.

so for example if you wanted to detect a swipe to the left I'd so following.

Declare two variables in the interface of you're class

CGPoint firstTouch;
CGPoint lastTouch;

In the init method of the implementation of your class enable touches

self.isTouchEnabled = YES;

3.Add these methods to your class

-(void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    NSSet *allTouches = [event allTouches];
    UITouch * touch = [[allTouches allObjects] objectAtIndex:0];
    CGPoint location = [touch locationInView: [touch view]];
    location = [[CCDirector sharedDirector] convertToGL:location];

    //Swipe Detection Part 1
    firstTouch = location;
}

-(void) ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    NSSet *allTouches = [event allTouches];
    UITouch * touch = [[allTouches allObjects] objectAtIndex:0];
    CGPoint location = [touch locationInView: [touch view]];
    location = [[CCDirector sharedDirector] convertToGL:location];

    //Swipe Detection Part 2
    lastTouch = location;

    //Minimum length of the swipe
    float swipeLength = ccpDistance(firstTouch, lastTouch);

    //Check if the swipe is a left swipe and long enough
    if (firstTouch.x > lastTouch.x && swipeLength > 60) {
        [self doStuff];
    }

}

the method "doStuff" is whats called if a left swipe has occurred.

like image 126
Alexander Blunck Avatar answered Oct 12 '22 06:10

Alexander Blunck