Detect when UIGestureRecognizer is up, down, left and right Cocos2d

前端 未结 7 1453
闹比i
闹比i 2020-12-01 09:28

I have a CCSprite that I want to move around using gestures. Problem is I\'m completely new to Cocos2D. I want my sprite to perform one action when the gesture is up, anothe

7条回答
  •  天涯浪人
    2020-12-01 09:58

    Even though there's lots of good info here, I couldn't find a quick answer that had it all.

    If you want to differentiate whether a swipe is left or right or up or down, you need to create a new UISwipeGestureRecognizer for each direction.

    However! This is not so bad, because you can route each of your gesture recognizers to the same selector, that can then use a switch statement as you might expect.

    First, add gesture recognizers for each direction and route them to the same selector:

    - (void)setupSwipeGestureRecognizers
    {
        UISwipeGestureRecognizer *rightSwipeGestureRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(userDidSwipeScreen:)];
        rightSwipeGestureRecognizer.direction = UISwipeGestureRecognizerDirectionRight;
        UISwipeGestureRecognizer *leftSwipeGestureRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(userDidSwipeScreen:)];
        leftSwipeGestureRecognizer.direction = UISwipeGestureRecognizerDirectionLeft;
        [self.view addGestureRecognizer:rightSwipeGestureRecognizer];
        [self.view addGestureRecognizer:leftSwipeGestureRecognizer];
    }
    

    Second, differentiate between the directions with a switch statement:

    - (void)userDidSwipeScreen:(UISwipeGestureRecognizer *)swipeGestureRecognizer
    {
        switch (swipeGestureRecognizer.direction) {
            case UISwipeGestureRecognizerDirectionLeft: {
                // Handle left
                break;
            }
            case UISwipeGestureRecognizerDirectionRight: {
                // Handle right
                break;
            }
            default: {
                break;
            }
        }
    }
    

提交回复
热议问题