Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting up buttons in SKScene

I'm discovering that UIButtons don't work very well with SKScene, So I'm attempting to subclass SKNode to make a button in SpriteKit.

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

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

like image 760
AlexHeuman Avatar asked Sep 29 '13 19:09

AlexHeuman


1 Answers

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);     fireNode.name = @"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 ([node.name isEqualToString:@"fireButtonNode"]) {          //do whatever...     } } 
like image 130
AndyOS Avatar answered Sep 22 '22 12:09

AndyOS