lisovaccaro
lisovaccaro

Reputation: 34016

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

Upvotes: 1

Views: 1685

Answers (3)

CloakedEddy
CloakedEddy

Reputation: 1995

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

Upvotes: 1

ABakerSmith
ABakerSmith

Reputation: 22979

You should add the UIButton programatically, instead of in IB, to the SKScene's SKView (in didMoveToView for example). You can then set the target for the button with button.addTarget:action:forControlEvents:. Just remember to call button.removeFromSuperview() in willMoveFromView otherwise you'll see the buttons in your next scene.

Upvotes: 0

Dharmesh Kheni
Dharmesh Kheni

Reputation: 71862

You can you touchesBegan for that.

Here is example code for you:

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {

    for touch: AnyObject in touches{
        let location = touch.locationInNode(self)
        if self.nodeAtPoint(location) == self.playButton{

              //your code
        }
    }
}

Upvotes: 3

Related Questions