当用户滑动屏幕的左半部分时,我试图在iOS 7 Sprite Kit中运行一个动作。
为了实现这一点,我创建了一个等待触摸事件的for循环,并且在触摸时,有一个if语句检查触摸位置是否小于视图边界的一半。 if语句本身正在正确执行(如果触摸在屏幕的右半部分启动,则else返回正确的NSLog)。但是,无论触摸发生在何处,都会调用UISwipeGestureRecognizer触发的操作。我在下面列出了一个代码示例。
是否有理由不按预期工作?
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[super touchesBegan:touches withEvent:event];
for (UITouch *touch in touches) {
CGPoint touchLocation = [touch locationInView:self.view];
NSLog(@"Touch location: %f, %f",touchLocation.x,touchLocation.y);
if (touchLocation.x<self.view.bounds.size.width/2) {
UISwipeGestureRecognizer *swipeRight = [[UISwipeGestureRecognizer alloc] initWithTarget:(self) action:@selector(screenSwipedRight)];
swipeRight.numberOfTouchesRequired = 1;
swipeRight.direction=UISwipeGestureRecognizerDirectionRight;
[self.view addGestureRecognizer:(swipeRight)];
UISwipeGestureRecognizer *swipeLeft = [[UISwipeGestureRecognizer alloc] initWithTarget:(self) action:@selector(screenSwipedLeft)];
swipeLeft.numberOfTouchesRequired = 1;
swipeLeft.direction=UISwipeGestureRecognizerDirectionLeft;
[self.view addGestureRecognizer:(swipeLeft)];
UISwipeGestureRecognizer *swipeUp = [[UISwipeGestureRecognizer alloc] initWithTarget:(self) action:@selector(screenSwipedUp)];
swipeUp.numberOfTouchesRequired = 1;
swipeUp.direction=UISwipeGestureRecognizerDirectionUp;
[self.view addGestureRecognizer:(swipeUp)];
}
else {
NSLog(@"Touches were on the right!");
}
}
}
-(void)screenSwipedRight
{
CGFloat percentToRight = 1-(self.playerOne.position.x / self.view.bounds.size.width);
NSTimeInterval timeToRight = self.horizontalRunSpeed * percentToRight;
NSLog(@"Percent to right = %f",percentToRight);
NSLog(@"Time to right = %f",timeToRight);
SKAction *moveNodeRight = [SKAction moveToX:self.view.bounds.size.width-self.playerOne.size.width duration:timeToRight];
[self.playerOne runAction:[SKAction sequence:@[moveNodeRight]]];
}
答案 0 :(得分:2)
是否有理由不按预期工作?
是。无论何时在屏幕的左半部分开始触摸,您都会添加一组新的滑动手势识别器。你永远不会删除它们。您永远不会限制手势识别器开始的条件。
这可以解决您的问题:
touchesBegan:withEvent:
。viewDidLoad
。delegate = self
。添加此代码:
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
CGPoint touchLocation = [touch locationInView:self.view];
NSLog(@"Touch location: %f, %f",touchLocation.x,touchLocation.y);
BOOL shouldBegin = (touchLocation.x < self.view.bounds.size.width / 2);
return shouldBegin;
}