【问题标题】:How to make a Toggle Button on SpriteKit如何在 SpriteKit 上制作切换按钮
【发布时间】:2013-10-30 16:26:58
【问题描述】:

我正在 SpriteKit 中做一个声音切换按钮,我正在尝试找到一种快速的方法来做到这一点。我记得在 Cocos2d 中有一个名为 CCMenuItemToggle 的变量可以生成所有的东西,例如:

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

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

【问题讨论】:

  • 您需要制作一个带有 2 个精灵/或标签的自定义按钮,每个用于状态。

标签: ios ipad sprite-kit


【解决方案1】:

将 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];
    }
}

【讨论】:

    猜你喜欢
    • 2023-03-10
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-24
    • 2012-06-13
    相关资源
    最近更新 更多