RayChen
RayChen

Reputation: 1468

How to limit touch duration?

Is there any method able to limit the duration of user gesture? For example, user can drag a sprite, but from cctouch begin, it only can last for 3 seconds. After the duration, the apps will auto trigger cctouch end method.

Upvotes: 1

Views: 132

Answers (2)

Lorenzo Linarducci
Lorenzo Linarducci

Reputation: 541

I would recommend scheduling a timer using blocks. Avoid using NSTimer with Cocos2D, as it does not allow for the built-in pause/resume functionality.

Schedule as follows:

- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event 
{
    [[self scheduler] scheduleBlockForKey:@"menu" target:self interval:3.0f repeat:0 delay:0 paused:NO block:^(ccTime dt)
             {
                 // perform end of touch actions here
             }];
}

Also be sure to unschedule the block if the user does whatever you want before the timer is called (ccTouchEnded/ccTouchCancelled is likely):

- (void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event 
{
    [[self scheduler] unscheduleBlockForKey:@"menu" target:self];
}

Upvotes: 2

Javier Quevedo
Javier Quevedo

Reputation: 2046

Yes, here is an easy strategy to achieve that. You can start a timer when the user begins to realise the gesture, and when the timer hits, stop it.

-(void) timerDidTick:(NSTimer *)theTimer{
    cpMouseRelease(mouse);
}

- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event {
    NSTimer *aTimer = [NSTimer timerWithTimeInterval:3.0 target:self selector:@selector(timerDidTick:) userInfo:nil repeats:NO] ;
    [[NSRunLoop mainRunLoop] addTimer:aTimer forMode:NSRunLoopCommonModes];
    CGPoint touchLocation = [self convertTouchToNodeSpace:touch];
    cpMouseGrab(mouse, touchLocation, false);
...
}

Upvotes: 2

Related Questions