Определить, когда UIGestureRecognizer вверх, вниз, влево и вправо Cocos2d - PullRequest
25 голосов
/ 14 сентября 2011

У меня есть CCSprite, который я хочу перемещать, используя жесты.Проблема в том, что я совершенно новичок в Cocos2D.Я хочу, чтобы мой спрайт выполнял одно действие, когда жест вверх, другое, когда жест вниз, другое действие, когда жест прав, и то же самое для левой.Может ли кто-нибудь указать мне правильное направление?

Спасибо!

Ответы [ 7 ]

57 голосов
/ 14 октября 2011

Очевидно, что каждый UISwipeGestureRecognizer может обнаруживать пролистывание только в заданном направлении. Несмотря на то, что флаги направления могут объединяться или объединяться, UISwipeGestureRecognizer игнорирует дополнительные флаги.

Решение состоит в том, чтобы добавить один UISwipeGestureRecognizer для каждого направления, в котором вы хотите распознать жест пролистывания, и установить направление каждого распознавателя соответственно вверх, вниз, влево и вправо. Если вы хотите проверить движение в любом направлении, вам нужно добавить четыре UISwipeGestureRecognizer.

Это немного странно, но это единственный способ, который сработал для меня.

27 голосов
/ 03 сентября 2012
UISwipeGestureRecognizer *swipeGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeGesture:)];
swipeGesture.direction = UISwipeGestureRecognizerDirectionUp|UISwipeGestureRecognizerDirectionDown;
[self.gestureAreaView addGestureRecognizer:swipeGesture];
[swipeGesture release];

-(void)handleSwipeGesture:(UISwipeGestureRecognizer *) sender 
{
    //Gesture detect - swipe up/down , can't be recognized direction
}

or

UISwipeGestureRecognizer *swipeGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeGesture:)];
swipeGesture.direction = UISwipeGestureRecognizerDirectionUp;
[self.view addGestureRecognizer:swipeGesture];
[swipeGesture release];

UISwipeGestureRecognizer *swipeGesture2 = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeGesture:)];
swipeGesture2.direction = UISwipeGestureRecognizerDirectionDown;
[self.view addGestureRecognizer:swipeGesture2];
[swipeGesture2 release];

-(void)handleSwipeGesture:(UISwipeGestureRecognizer *) sender 
{
    //Gesture detect - swipe up/down , can be recognized direction
    if(sender.direction == UISwipeGestureRecognizerDirectionUp)
    {
    }
    else if(sender.direction == UISwipeGestureRecognizerDirectionDown)
    {
    }
}
8 голосов
/ 28 января 2013

Используйте UIPanGestureRecogizer и определите направления движения, которые вас интересуют.подробности смотрите в документации к UIPanGestureRecognizer.-rrh

// add pan recognizer to the view when initialized
UIPanGestureRecognizer *panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panRecognized:)];
[panRecognizer setDelegate:self];
[self addGestureRecognizer:panRecognizer]; // add to the view you want to detect swipe on


-(void)panRecognized:(UIPanGestureRecognizer *)sender
{
    if (sender.state == UIGestureRecognizerStateBegan) {
        // you might want to do something at the start of the pan
    }

    CGPoint distance = [sender translationInView:self]; // get distance of pan/swipe in the view in which the gesture recognizer was added
    CGPoint velocity = [sender velocityInView:self]; // get velocity of pan/swipe in the view in which the gesture recognizer was added
    float usersSwipeSpeed = abs(velocity.x); // use this if you need to move an object at a speed that matches the users swipe speed
    NSLog(@"swipe speed:%f", usersSwipeSpeed);
    if (sender.state == UIGestureRecognizerStateEnded) {
        [sender cancelsTouchesInView]; // you may or may not need this - check documentation if unsure
        if (distance.x > 0) { // right
            NSLog(@"user swiped right");
        } else if (distance.x < 0) { //left
            NSLog(@"user swiped left");
        }
        if (distance.y > 0) { // down
            NSLog(@"user swiped down");
        } else if (distance.y < 0) { //up
            NSLog(@"user swiped up");
        }
        // Note: if you don't want both axis directions to be triggered (i.e. up and right) you can add a tolerence instead of checking the distance against 0 you could check for greater and less than 50 or 100, etc.
    }
}
7 голосов
/ 22 марта 2012

Направление по умолчанию - UISwipeGestureRecognizerDirectionRight. Несколько направлений также могут быть указаны так:

[swipeGesture setDirection: UISwipeGestureRecognizerDirectionRight|UISwipeGestureRecognizerDirectionLeft];

/// Но если вы хотите получить каждое направление, например:

 UISwipeGestureRecognizer *swipeGestureR = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeGestureRight:)];
[swipeGestureR setDirection: UISwipeGestureRecognizerDirectionRight ];
 [[[CCDirector sharedDirector] openGLView] addGestureRecognizer:swipeGestureR];

[swipeGestureR release];

UISwipeGestureRecognizer *swipeGestureL = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeGestureLeft:)];
[swipeGestureL setDirection: UISwipeGestureRecognizerDirectionLeft];
[[[CCDirector sharedDirector] openGLView] addGestureRecognizer:swipeGestureL];

[swipeGestureL release];

функция handleSwipeGestureLeft будет вызываться при перемещении влево, а handleSwipeGestureRight будет вызываться при перемещении вправо

1 голос
/ 06 мая 2015

Добавьте один UISwipeGestureRecognizer для каждого топора (горизонтальный и вертикальный):

UISwipeGestureRecognizer *horizontalSwipe = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(action)];
[horizontalSwipe setDirection:(UISwipeGestureRecognizerDirectionRight |
                           UISwipeGestureRecognizerDirectionLeft )];

[self.view addGestureRecognizer:horizontalSwipe];

UISwipeGestureRecognizer *verticalSwipe = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(action)];
[verticalSwipe setDirection:(UISwipeGestureRecognizerDirectionUp |
                     UISwipeGestureRecognizerDirectionDown )];

[self.view addGestureRecognizer:verticalSwipe];
0 голосов
/ 11 марта 2016

Несмотря на то, что здесь есть много полезной информации, я не смог найти быстрого ответа, в котором бы было все это.

Если вы хотите различить, является ли пролистывание left или rightили up или down, вам нужно создать новый UISwipeGestureRecognizer для каждого направления.

Однако!Это не так уж и плохо, потому что вы можете направить каждый из ваших распознавателей жестов к одному и тому же селектору , который затем может использовать оператор switch, как вы могли ожидать.

Первый , добавьте распознаватели жестов для каждого направления и направьте их к одному и тому же селектору:

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

Секунда , различайте направления с помощью оператора switch:

- (void)userDidSwipeScreen:(UISwipeGestureRecognizer *)swipeGestureRecognizer
{
    switch (swipeGestureRecognizer.direction) {
        case UISwipeGestureRecognizerDirectionLeft: {
            // Handle left
            break;
        }
        case UISwipeGestureRecognizerDirectionRight: {
            // Handle right
            break;
        }
        default: {
            break;
        }
    }
}
0 голосов
/ 14 сентября 2011
-(void)addGesture {
UISwipeGestureRecognizer *swipeGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeGesture:)];
    [self.view addGestureRecognizer:swipeGesture];
    [swipeGesture release];
}

-(void)handleSwipeGesture:(UISwipeGestureRecognizer *) sender {

if (sender.direction == UISwipeGestureRecognizerDirectionUp) {
  //do something
 }
else if (sender.direction == UISwipeGestureRecognizerDirectionDown) {
  //do something
 }
else if (sender.direction == UISwipeGestureRecognizerDirectionLeft) {
  //do something
 }
else if (sender.direction == UISwipeGestureRecognizerDirectionRight) {
  //do something
 }


}

Можно также использовать переключатель вместо всех операторов if

...