Обнаруживать, когда UIGestureRecognizer вверх, вниз, влево и вправо Cocos2d
У меня есть CCSprite, который я хочу перемещать, используя жесты. Проблема в том, что я совершенно не знаком с Cocos2D. Я хочу, чтобы мой спрайт выполнил одно действие, когда жест поднят, еще один, когда жест остановлен, другое действие, когда жест прав и то же самое для левой. Может ли кто-нибудь указать мне в правильном направлении?
Спасибо!
Ответы
Ответ 1
По-видимому, каждый UISwipeGestureRecognizer может обнаруживать только салфетки в данном направлении. Несмотря на то, что флаги направления могут быть OR' вместе, UISwipeGestureRecognizer игнорирует дополнительные флаги.
Решение состоит в том, чтобы добавить один UISwipeGestureRecognizer для каждого направления, в котором вы хотите распознать жестом салфетки, и установить каждое направление распознавания соответственно вверх, вниз, влево и вправо. Если вы хотите протестировать салфетки в любом направлении, вам придется добавить четыре UISwipeGestureRecognizers.
Это как-то странно, но единственный способ, которым это работало для меня.
Ответ 2
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)
{
}
}
Ответ 3
Используйте 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.
}
}
Ответ 4
Направление деактивации - 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 будет вызываться при прокрутке вправо
Ответ 5
Добавьте один 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];
Ответ 6
-(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
Ответ 7
Несмотря на то, что здесь много хорошей информации, я не мог найти быстрый ответ, в котором все было бы.
Если вы хотите различить, имеет ли прокрутка 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;
}
}
}