2014-01-05 131 views
0

我在_background(綠色)上添加了兩個精靈,並試圖通過將手指拖動到它們上來選擇精靈。使用nodeAtPoint選擇我用手指觸摸的精靈不選擇精靈

[_background addChild:S1]; 
[_background addChild:S2]; 

enter image description here

我使用的方法從這樣一個問題:select all the sprites my finger touches while moving

我沒有得到實際的飛船精靈一擊,只有背景。

我用的是代碼:

- (void)handlePan:(UIPanGestureRecognizer *)sender { 
    _touchLocation = [sender locationInView:sender.view]; 
    _touchLocation = [self convertPointFromView:_touchLocation]; 

... 

if (sender.state == UIGestureRecognizerStateBegan) { 
       NSLog(@"UIGestureRecognizerStateBegan"); 
       //////Make sure that no sprites are moved during the selecting phase////// 
       _background.userInteractionEnabled = NO; 
      } else if (sender.state == UIGestureRecognizerStateChanged) { 
       NSLog(@"UIGestureRecognizerStateChanged"); 
       SKNode *node = [_background nodeAtPoint:[self convertPointFromView:_touchLocation]]; 
       //if (![node.name isEqualToString:@"background"]) { 
        NSLog(@"Selected node:%@", node.name); 
       //} 
      } else if (sender.state == UIGestureRecognizerStateEnded) { 
       NSLog(@"UIGestureRecognizerStateEnded"); 
       _background.userInteractionEnabled = YES; 
      } 
... 

結果:

2014-01-05 21:38:34.011 xxxxx[21172:a0b] UIGestureRecognizerStateBegan 
2014-01-05 21:38:36.513 xxxxx[21172:a0b] UIGestureRecognizerStateChanged 
2014-01-05 21:38:36.514 xxxxx[21172:a0b] Selected node:background 
2014-01-05 21:38:36.545 xxxxx[21172:a0b] UIGestureRecognizerStateChanged 
2014-01-05 21:38:36.546 xxxxx[21172:a0b] Selected node:background 
2014-01-05 21:38:36.578 xxxxx[21172:a0b] UIGestureRecognizerStateChanged 
2014-01-05 21:38:36.579 xxxxx[21172:a0b] Selected node:background 
… 
2014-01-05 21:38:36.987 xxxxx[21172:a0b] UIGestureRecognizerStateEnded 

我沒能獲得在太空船一擊時,我對他們動了我的手指。

我如何創建UIPanGestureRecognizer

_panGesture = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(handlePan:)]; 
[self.view addGestureRecognizer:_panGesture]; 
+0

show me code如何創建UIPanGestureRecognizer對象? – Tirth

+0

@Reformer見上面 – PeterK

+0

認真!!如果我在cocos2d中做這樣的任務,那麼我將不會使用gestureRecognizer類型的東西。 Cocos2d爲我們提供了觸摸檢測圖像的事件方法。看到這個tut的參考http://www.raywenderlich.com/2343/cocos2d-tutorial-for-ios-how-to-drag-and-drop-sprites – Tirth

回答

0

你這樣做的方法開始:

_touchLocation = [self convertPointFromView:_touchLocation]; 

你再這樣做以後:

SKNode *node = [_background nodeAtPoint:[self convertPointFromView:_touchLocation]]; 

我的猜測是,轉換點兩次可能會給你的W榮位置。你應該記錄點,看看他們是否正確。

如果不是這樣,那麼也許你需要將位置轉換爲船父節點空間。如下:

_touchLocation = [_background convertPoint:_touchLocation toNode:_background]; 
+0

謝謝,那是問題所在。 – PeterK