在Cocos2d中滑动

时间:2012-02-02 13:03:18

标签: cocos2d-iphone

我想让刷卡工作为Cocos2d最新版本,这是我的代码:

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

    [swipeLeft setDirection:UISwipeGestureRecognizerDirectionLeft];

    [swipeLeft setNumberOfTouchesRequired:1];

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


}

根本没有检测到滑动!

更新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];


}

2 个答案:

答案 0 :(得分:11)

我也尝试过这项工作,但我发现了一种更简单,也更好的控制方法。

所以,例如,如果您想要检测左侧的滑动,我会这么跟随。

在你的类

的界面中声明两个变量
CGPoint firstTouch;
CGPoint lastTouch;

在你的类的实现的init方法中启用touches

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”。

答案 1 :(得分:3)

代码是正确的,应该有效。

您可能想验证gl视图或主窗口上是否禁用了userInteraction和touch输入。

你还应该检查cocos2d是否正在以某种方式吃掉它。 EAGLView类是触摸的第一个接收器,并将它们转发到CCTouchDispatcher。我可以想象,如果你有针对性的触摸代表他们可能会吞下"接触。虽然cocos2d只应在手势识别器之后才能接收到触摸。