2012-02-02 68 views
6

我試圖讓刷卡爲這裏的Cocos2D最新版本的工作是我的代碼:滑動操作在Coco2d

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

    [swipeLeft setDirection:UISwipeGestureRecognizerDirectionLeft]; 

    [swipeLeft setNumberOfTouchesRequired:1]; 

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


} 

它沒有檢測到刷卡了!

UPDATE 1:

我更新的代碼下面,並且仍然沒有檢測到掃動。

-(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]; 


} 

回答

11

我試着做這個工作,但我發現更容易和更好的控制方法。

因此,例如,如果你想檢測左邊的滑動,我會如此。

聲明兩個變量在你的界面是類

CGPoint firstTouch; 
CGPoint lastTouch; 

在你的類的實現的init方法使觸摸

self.isTouchEnabled = YES; 

3.添加這些方法你

-(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]; 
    } 

} 

方法「doStuff」是如果左側滑動已發生時所謂的。

+0

我更喜歡使用UIGestureRecognizer,因爲它很容易創建不同類型的觸摸事件。 – azamsharp 2012-02-02 19:16:08

+2

這是天才! – 2012-11-17 07:04:46

3

該代碼是正確的,應該工作。

您可能想要驗證在gl視圖或主窗口上是否禁用userInteraction和觸摸輸入。

您還應該檢查cocos2d是否以某種方式進行觸摸。 EAGLView類是觸摸的第一個接收器,並將它們轉發給CCTouchDispatcher。我可以想象,如果你有針對性的接觸代表他們可能會「吞下」觸摸。儘管cocos2d只能在手勢識別器之後才能接受觸摸。

+0

我更新了原始問題中的代碼,但仍未檢測到刷卡。 – azamsharp 2012-02-03 01:17:40