触摸*事件 - SKScene与ViewController

时间:2014-08-28 09:45:32

标签: sprite-kit skscene

我有一个经典的SKScene,带有一些按钮(全部以编程方式制作)和ViewController用于该场景。应该触摸哪些事件处理 - 在SKScene或ViewController中。当通过push segue触摸不同的按钮时,我需要切换到另一个场景和另一个视图控制器。当我在视图控制器中处理触摸事件时,它返回我为触摸的SKNode为零。这是我在视图控制器中的代码(场景是它的属性):

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
   UITouch *touch = [touches anyObject];
   CGPoint location = [touch locationInNode:self.scene];
   SKNode *node = [self.scene nodeAtPoint:location];
   if ([node.name  isEqual: @"campaign"]) {
       CampaignViewController *levelViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"CampaignScene"];
       [self.navigationController pushViewController:levelViewController animated:NO];
   }
}

感谢您的解释。

1 个答案:

答案 0 :(得分:4)

在ViewController中实现触摸委托不可能为您提供节点,因为它是管理它们的SKScene。因此,为了能够使用nodeAtPoint:,您需要在SKScene中实现触摸代理。

现在,您还需要一种让SKScene与UIViewController通信的方法,并传递将触发segues或其他方法的消息。为此,您可以使用Delegation或NSNotificationCenter,其实现在此answer中进行了演示。

在您实现了答案中的任何一个选项后,您的代码应如下所示:

//In ViewController.m

-(void) presentCampaignVieController
{
     CampaignViewController *levelViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"CampaignScene"];
     [self.navigationController pushViewController:levelViewController animated:NO];
}

//In SKScene.m (Using Delegation)

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
   UITouch *touch = [touches anyObject];
   CGPoint location = [touch locationInNode:self.scene];
   SKNode *node = [self.scene nodeAtPoint:location];
   if ([node.name  isEqual: @"campaign"]) {
       [self.delegate presentCampaignVieController];
   }
}

为了使用NSNotificationCenter在viewController中调用相同的方法,首先必须添加一个观察者:

//ViewController.m, under viewDidLoad
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(presentCampaignVieController) name:@"gotoCampaign" object:nil];

//In SKScene.m (Using NSNotificationCenter)
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
   UITouch *touch = [touches anyObject];
   CGPoint location = [touch locationInNode:self.scene];
   SKNode *node = [self.scene nodeAtPoint:location];
   if ([node.name  isEqual: @"campaign"])
   {
       [[NSNotificationCenter defaultCenter] postNotificationName:@"gotoCampaign" object:nil];
   }
}