如何在SpriteKit上做一个切换button
我在SpriteKit中做了一个声音切换button,我试图find一个快速的方法来做到这一点。 我记得在Cocos2d中有一个名为CCMenuItemToggle
的variables,它使得所有的东西,例如:
CCMenuItemToggle* musicButtonToggle = [CCMenuItemToggle itemWithItems:[NSArray arrayWithObjects:soundButtonOn,soundButtonOff, nil] block:^(id sender) { [self stopSounds]; }];
任何人都知道在SpriteKit上做到这一点?
基本切换button子类SKLabelNode
。H
typedef NS_ENUM(NSInteger, ButtonState) { On, Off }; @interface ToggleButton : SKLabelNode - (instancetype)initWithState:(ButtonState) setUpState; - (void) buttonPressed; @end
.M
#import "ToggleButton.h" @implementation ToggleButton { ButtonState _currentState; } - (id)initWithState:(ButtonState) setUpState { if (self = [super init]) { _currentState = setUpState; self = [ToggleButton labelNodeWithFontNamed:@"Chalkduster"]; self.text = [self updateLabelForCurrentState]; self.fontSize = 30; } return self; } - (NSString *) updateLabelForCurrentState { NSString *label; if (_currentState == On) { label = @"ON"; } else if (_currentState == Off) { label = @"OFF"; } return label; } - (void) buttonPressed { if (_currentState == Off) { _currentState = On; } else { _currentState = Off; } self.text = [self updateLabelForCurrentState]; } @end
添加一个切换button到你的场景
ToggleButton *myLabel = [ToggleButton new]; myLabel = [myLabel initWithState:Off]; myLabel.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame)); [self addChild:myLabel];
检测触摸
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { UITouch* touch = [touches anyObject]; CGPoint loc = [touch locationInNode:self]; SKNode *node = [self nodeAtPoint:loc]; if ([node isKindOfClass:[ToggleButton class]]) { ToggleButton *btn = (ToggleButton*) node; [btn buttonPressed]; } }