ios - 如何在 SpriteKit 上制作切换按钮

标签 ios ipad sprite-kit

我正在 SpriteKit 中做一个声音切换按钮,我正试图找到一种快速的方法来完成它。我记得在 Cocos2d 中有一个名为 CCMenuItemToggle 的变量,它制作了所有东西,例如:

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

有人知道在 SpriteKit 上执行此操作的方法吗?

最佳答案

子类化 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];
    }
}

关于ios - 如何在 SpriteKit 上制作切换按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19688451/

相关文章:

xcode - resignFirstResponder 没有在 textFieldShouldReturn 上隐藏键盘

html - 在 iPad 上滚动

ios - 在我的Xcode项目中找不到<libxml2/tree.h>

ios - AdMob Interstitial 每五场比赛一次

ios - 有没有办法使 SKSpriteNode 旋转与另一个 SKSpriteNode 物理体平行?

iphone - 发布前更新 iPhone 应用程序

ios - iOS 14 上的多播网络授权

swift - 给 Sprite 着色与其纹理不同的颜色

ios - 我如何从这个 Swift 类创建一个基类以便它可以被继承?

ios - 如何从字典中获取值