AlexHeuman AlexHeuman - 4 months ago 6x
iOS Question

Setting up buttons in SKScene

I'm discovering that

don't work very well with
, So I'm attempting to subclass
to make a button in

The way I would like it to work is that if I initialize a button in
and enable touch events, then the button will call a method in my
when it is pressed.

I'd appreciate any advice that would lead me to finding the solution to this problem. Thanks.


you could use a SKSpriteNode as your button, and then when the user touches, check if that was the node touched. Use the SKSpriteNode's name property to identify the node:

//fire button
- (SKSpriteNode *)fireButtonNode
    SKSpriteNode *fireNode = [SKSpriteNode spriteNodeWithImageNamed:@"fireButton.png"];
    fireNode.position = CGPointMake(fireButtonX,fireButtonY); = @"fireButtonNode";//how the node is identified later
    fireNode.zPosition = 1.0;
    return fireNode;

Add node to your scene:

[self addChild: [self fireButtonNode]];

Handle touches:

//handle touch events
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInNode:self];
    SKNode *node = [self nodeAtPoint:location];

    //if fire button touched, bring the rain
    if ([ isEqualToString:@"fireButtonNode"]) {
         //do whatever...