如何区分点按并保持?

时间:2014-09-19 22:17:26

标签: ios objective-c cocos2d-iphone

在我的游戏中,我有两种类型的手势;单击并按住。当我将手指放在屏幕上时,它会调用touchBegan:(UITouch *)touch withEvent:(UIEvent *)event来调用我的tapped方法,因此两个手势都被调用。我该如何避免这个问题?我是否必须使用UIGestureRecognizers或者有没有办法只使用内置的cocos2d方法?我需要专门调用这些手势,而不是相互结合。

typedef NS_ENUM(NSUInteger, BPMovementState) {
    kTouchUp,  //Finger is not on the screen
    kTouchDown //Finger is on the screen
};

 @implementation HelloWorldScene
{
    CCSprite *_hero;
    BPMovementState _touchState;
}

- (instancetype)init

    self = [super init];
    if (!self) return(nil);

    // Enable touch handling on scene node
    self.userInteractionEnabled = YES;

    _touchState = kTouchUp;

    return self;
}

- (void)fixedUpdate:(CCTime)delta{

     if(_touchState == kTouchDown){
         //_hero slide
         _hero.position = ccp(_hero.position.x + 1, _hero.position.y);
     }

}

-(void) touchBegan:(UITouch *)touch withEvent:(UIEvent *)event {

    _touchState = kTouchDown;
   if(touch.tapCount == 1)
        [_hero jump]

}

- (void)touchEnded:(UITouch *)touch withEvent:(UIEvent *)event{


    _touchState = kTouchUp;

}

2 个答案:

答案 0 :(得分:1)

可以通过以下方式实现。

在标题I.e touchTimer中定义一个计时器

在touchBegan中启动计时器

touchTimer = [NSTimer scheduledTimerWithTimeInterval:延迟目标:自选择器:@selector(touchHasBeenHeld :) userInfo:nil重复:否];

如果计时器到期并且在触摸释放之前调用了选择器-touchHasBeenHeld id。举办活动。 在这里你也使计时器无效。

否则,如果调用-touchEnded并且计时器仍然有效,则触摸事件。 再次使计时器无效。

答案 1 :(得分:0)

如果可以,我会坚持使用UIGestureRecognizer。 Apple的手势识别器经过调整,让用户感觉很熟悉。如果您创建自己的,您的时间或阈值可能会略有不同,并且对于习惯于系统默认的用户,手势会感到奇怪。 Here是一个关于向{cocos2d项目添加UIGestureRecognizer的快速教程。