作者热门文章
- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
我正在 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/
我是一名优秀的程序员,十分优秀!