我正在SpriteKit中做一个声音切换按钮,我正试图找到一个快速的方法来做到这一点。我记得在Cocos2d中有一个名为CCMenuItemToggle
的变量可以完成所有的工作,例如:
CCMenuItemToggle* musicButtonToggle = [CCMenuItemToggle
itemWithItems:[NSArray arrayWithObjects:soundButtonOn,soundButtonOff, nil]
block:^(id sender)
{
[self stopSounds];
}];
任何人都知道在SpriteKit上执行此操作的方法吗?
答案 0 :(得分:6)
基本切换按钮对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
向场景中添加切换按钮
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];
}
}