Search code examples
xcodeswiftsprite-kitskscene

Detecting when a button is touched in SKScene?


I created a storyboard and added a scene with two buttons. I cannot figure out how to know when a button is pressed on my GameScene.swift class.

How can this be done?

enter image description here


Solution

  • You appear to be mixing UIKit and SpriteKit here. I would personally advise against using UIButtons in conjunction with Sprite Kit. Is there a specific reason for doing so?

    There are two ways you can implement button behavior within a Sprite Kit scene:

    1. have the SKScene object handle the touches
    2. have the button itself handle the touches

    Dharmesh's answer uses method (1), where he implements the -touchesBegan method. In my current project, I am using an SKNode subclass as a button (2). I am unfamiliar with Swift syntax so I have posted Objective-C code from my project instead. The method calls are similar though and should help illustrate the point.

    If you want an SKNode to receive touches, set userInteractionEnabled to YES. Otherwise, the closest ancestor with userInteractionEnabled = YES (which typically is the containing SKScene) will receive a -touchesBegan/-touchesMoved/-touchesEnded message.

    @interface VTObject : SKNode
    
    @end
    
    ...
    
    @implementation VTObject
    
    - (instancetype)init {     
      if (self = [super init]) {
        self.userInteractionEnabled = YES;
      }
    
      return self;
    }
    
    - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {    
      NSLog(@"button touched!");
    }
    
    @end