2013-12-14 48 views
4

我正在構建一個基於sprite kit的遊戲,而缺少「右鍵單擊」實際上很難將一些重要信息傳達給我的用戶。作爲一種解決方案,我正在考慮長按,兩指輕敲等手勢。iOS7 Sprite Kit如何在SKSpriteNode上長按或其他手勢?

如何在SKSpriteNode上實現手勢?

這是我目前用來獲取觸摸SKSpriteNode時按鈕狀行爲。

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { 
    [self selectSkill:YES]; 
} 

回答

0

有沒有簡單的方法來做到這一點,但我能想到的一個方法是將一個子SKView添加到您的SKScene並放置一個的UIImageView作爲SKView裏面的唯一的事情。然後,您可以添加一個像SKView一樣正常的手勢識別器。

這裏就是我談論的例子:

UIImageView *button = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"ButtonSprite"]]; 

SKView *spriteNodeButtonView = [[SKView alloc] initWithFrame:CGRectMake(100, 100, button.frame.size.width, button.frame.size.height)]; 

UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(someMethod:)]; 
[spriteNodeButtonView addGestureRecognizer:tap]; 

[spriteNodeButtonView addSubview:button]; 

你可以把SKView無論你想和使用任何手勢識別器上SKView:UITapGestureRecognizerUILongPressGestureRecognizerUISwipeGestureRecognizerUIPinchGestureRecognizerUIRotationGestureRecognizerUIPanGestureRecognizer或​​。

那麼對於你的方法實現做這樣的事情:

-(void)someMethod:(UITapGestureRecognizer *)recognizer { 
    CGPoint touchLoc = [recognizer locationInView:self.view]; 
    NSLog(@"You tapped the button at - x: %f y: %f", touchLoc.x, touchLoc.y); 
} 
+0

您還可以看看[此帖](http://stackoverflow.com/questions/19082202/spritekit-setting-up-buttons-in-skscene)。有人創建了一個SKButton類,它只是創建一個像UIButton一樣工作的SKSpriteNode。如果你想使用更像按鈕的東西..我使用他的SKButton類,它適用於我迄今爲止需要的一切,但我不需要使用任何手勢識別器。 – Ponyboy47

2

UIGestureRecognizer之前,你留了追蹤狀態變量,其中接觸在何時何地開始。這裏有一個快速的解決方案,其中buttonTouched:是一個方法,用於檢查UITouch是否在您正在檢查的按鈕上。

var touchStarted: NSTimeInterval? 
let longTapTime: NSTimeInterval = 0.5 

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) { 
    if let touch = touches.anyObject() as? UITouch { 
     if buttonTouched(touch) { 
      touchStarted = touch.timestamp 
     } 
    } 
} 

override func touchesEnded(touches: NSSet, withEvent event: UIEvent) { 
    if let touch = touches.anyObject() as? UITouch { 
     if buttonTouched(touch) && touchStarted != nil { 
      let timeEnded = touch.timestamp 
      if timeEnded - touchStarted! >= longTapTime { 
       handleLongTap() 
      } else { 
       handleShortTap() 
      } 
     } 
    } 
    touchStarted = nil 
} 

override func touchesCancelled(touches: NSSet!, withEvent event: UIEvent!) { 
    touchStarted = nil 
}