如何在SpriteKit上创建一个切换按钮

Ver*_*ort 4 ipad ios sprite-kit

我正在SpriteKit中做一个声音切换按钮,我正试图找到一个快速的方法来做到这一点.我记得在Cocos2d中有一个叫做CCMenuItemToggle所有东西的变量,例如:

CCMenuItemToggle* musicButtonToggle = [CCMenuItemToggle
                                               itemWithItems:[NSArray arrayWithObjects:soundButtonOn,soundButtonOff, nil]
                                               block:^(id sender)
                                               {
                                                   [self stopSounds];
                                               }];
Run Code Online (Sandbox Code Playgroud)

有人知道在SpriteKit上做这个的方法吗?

Dog*_*fee 6

基本切换按钮子类化SKLabelNode

.H

typedef NS_ENUM(NSInteger, ButtonState)
{
    On,
    Off
};

@interface ToggleButton : SKLabelNode

- (instancetype)initWithState:(ButtonState) setUpState;
- (void) buttonPressed;

@end
Run Code Online (Sandbox Code Playgroud)

.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
Run Code Online (Sandbox Code Playgroud)

在场景中添加切换按钮

ToggleButton *myLabel = [ToggleButton new];
myLabel = [myLabel initWithState:Off];
myLabel.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame));
[self addChild:myLabel];
Run Code Online (Sandbox Code Playgroud)

检测触摸

-(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];
    }
}
Run Code Online (Sandbox Code Playgroud)