gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 05:29:47 26 4
gpt4 key购买 nike

我正在 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com