无法点击SKSpriteNode – 没有触摸检测到ios

我对iOS,Objective C非常新,并且使用Xcode。 我只做了一个简单的新闻类应用程序,但现在我想创build一个我在另一个平台上发布的游戏。

基本上,我有一个物体随机出现,然后淡出,目的是挖掘物体使其消失。

不过,我似乎无法挖掘该对象,即使我设置mySKSpriteNode.userInteractionEnabled = YES;

这是我在touchesBegan方法中所具有的:

 -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { /* Called when a touch begins */ NSLog(@"Something was touched"); UITouch *touch = [touches anyObject]; NSLog(@"%@", touch); CGPoint location = [touch locationInNode:self]; SKNode *node = [self nodeAtPoint:location]; if(node == mySKSpriteNode) [node runAction:[SKAction fadeOutWithDuration:0]]; } 

在我的日志中,当我点击屏幕(而不是我拥有对象的地方)时,

 2014-02-17 23:18:30.870 BubbleChallenge[48541:70b] Something was touched 2014-02-17 23:18:30.875 BubbleChallenge[48541:70b] <UITouch: 0x1130ea530> phase: Began tap count: 1 window: <UIWindow: 0x109c2ab60; frame = (0 0; 320 568); autoresize = W+H; gestureRecognizers = <NSArray: 0x109c274d0>; layer = <UIWindowLayer: 0x109c26810>> view: <SKView: 0x109c2e5e0; frame = (0 0; 320 568); autoresize = RM+BM; layer = <CAEAGLLayer: 0x109c0e180>> location in window: {147.5, 128.5} previous location in window: {147.5, 128.5} location in view: {147.5, 128.5} previous location in view: {147.5, 128.5} 

当我触摸mySKSpriteNode时,我什么都没有在日志中,甚至没有“被触动”;

任何想法为什么会发生这种情况?

我发现的其他问题说,答案是设置userInteractionEnabled = YES ….也许在代码中有一个特定的点,我应该设置这个?

所有帮助表示赞赏!

你有没有尝试设置你的spritenode的name属性?

在初始化mySKSpriteNode

 mySKSpriteNode = [[SKSpriteNode alloc] initWithTexture:sometexture]; mySKSpriteNode.name = @"thisIsMySprite"; // set the name for your sprite mySKSpriteNode.userInteractionEnabled = NO; // userInteractionEnabled should be disabled 

然后:

 -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { UITouch *touch = [touches anyObject]; CGPoint location = [touch locationInNode:self]; SKNode *node = [self nodeAtPoint:location]; if ([node.name isEqualToString:@"thisIsMySprite"]) { NSLog(@"mySKSpriteNode was touched!"); [node runAction:[SKAction fadeOutWithDuration:0]]; } } 

你的代码基本上是正确的。 只需要一些小的改变。

你已经在场景类中实现了-touchesBegan:方法。 如果要处理场景类中的触摸,则所有子节点都应将userInteractionEnabled属性设置为NO 。 一个精灵节点的userInteractionEnabled属性应该被设置为YES只有当它能够处理它自己的触摸。

所以,在你的情况下,你应该做出以下改变:

1 – 将spriteNode的userInteraction设置为NO。

 mySKSpriteNode.userInteractionEnabled = NO; 

2 – 改变你检查自己的精灵的方式。

 if([node isEqual: mySKSpriteNode]) 

你会发现你的代码正在按预期工作。

在Swift 2.0中!

 override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { let touch = touches.first! let location = touch.locationInNode(self) let node = self.nodeAtPoint(location) if node.name == "spriteName" { // Present new game scene } } 

我从来没有使用SKSprite框架,但我会尽力帮助。 首先,你的函数“ – (void)touchesBegan:(NSSet *)与事件触发:(UIEvent *)事件”必须在您的自定义SKSpriteNode类中设置,如果不是这是正常的,如果不起作用。

如果已经完成,则必须searchtap的处理位置(通过其他对象),则可以使用:“ – (BOOL)gestureRecognizer:(UIPanGestureRecognizer )gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer 🙁 UISwipeGestureRecognizer )otherGestureRecognizer”

希望能帮助!