I have a reference to my class called TBButton. The TBButton is a subclass is SKSpriteNode, and has an enum with several types (one being "Blue"). How would I create a touchesBegan() function that gets called when any instance of that TBButton class gets touched? I've tried implementing a very simple touchesBegan() with an NSLog() inside the TBButton class itself, but that didn't work. I've also tried finding if the touched button in the GameScene.m is an instance of TBButton with this code:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
for (UITouch *touch in touches) {
CGPoint location = [touch locationInNode:self];
TBButton *touchedNode = (TBButton *)[self nodeAtPoint:location];
if (touchedNode && [touchedNode.name isEqualToString:@"button"]) {
if (touchedNode.type == Blue) {
// Touched a blue button.
NSLog(@"Touched a blue button");
/// Find out how to do this code! It ain't workin!
}
}
}
}
That was the code I tried inside my GameScene.m, but that didn't log anything to the console when I'd touch one of my buttons. Yes, I have made sure that the name of the TBButton instance was @"button", so that's not the problem.
To make things easier on me, please ignore any code inside the GameScene.m if that's not necessary. What I'm really wondering is if I can somehow implement a touchesBegan() function inside my TBButton.m itself! Or can I not? Would putting an instance method inside TBButton.h, setting it up to do the code when the button is touched in TBButton.m, and calling it when its instance inside GameScene.m work?
Hopefully you understand my question!
I gather your main issue is one of identification. SKSpriteNode being a subclass of SKNode you have 2 easy options:
When you create an instance of TBButton set the name property to something like "TBButton". You can then check for the node's name in the touchesBegan method.
If you require more than just a simple string, you can use the userData property of SKNode. Again, when creating an instance of TBButton:
Checking in touchesBegan would look something like this: