我目前正在使用委托和SKView自定义类来监控我的OS X SpriteKit游戏中的按键。我需要为我的键盘监视类使用多个代理,但我知道这是不可能的,但可以通过使用观察者实现。如何完成这个任务?这是使用委托模式的代码:
CustomSKView.h
#import <SpriteKit/SpriteKit.h>
@protocol KeyPressedDelegate;
@interface CustomSKView : SKView
@property (weak) id <KeyPressedDelegate> delegate;
@end
@protocol KeyPressedDelegate
- (void) upArrowPressed;
- (void) downArrowPressed;
@end
CustomSKView.m
#import "CustomSKView.h"
@implementation CustomSKView:SKView {
// Add instance variables here
}
- (id) initWithCoder:(NSCoder *)coder {
self = [super initWithCoder:coder];
if (self) {
// Allocate and initialize your instance variables here
}
return self;
}
- (void) keyDown:(NSEvent *)theEvent {
// Add code to handle a key down event here
if (self.delegate) {
switch (theEvent.keyCode) {
case 126: {
NSLog(@"delegate = %@", [self delegate]);
[self.delegate upArrowPressed];
break;
}
case 125:
[self.delegate downArrowPressed];
break;
default:
break;
}
}
}
@end
GameScene.h
#import <SpriteKit/SpriteKit.h>
#import "CustomSKView.h"
@interface GameScene : SKScene <KeyPressedDelegate>
@end
GameScene.m
#import "GameScene.h"
@implementation GameScene
-(void)didMoveToView:(SKView *)view {
((CustomSKView *)view).delegate = self;
}
- (void) upArrowPressed {
NSLog(@"Up Arrow Pressed");
}
- (void) downArrowPressed {
NSLog(@"Down Arrow Pressed");
}
@end
CustomSKView
类中创建一个数组,然后在它们各自的类中将每个场景或任何其他对象添加到其中,对吗?从那里开始,在CustomSKView
类中,我会运行一个循环通知所有代理,对吗? - 02fentymNSNotificationCenter
,这是你想要使用的。有很多好的教程可以参考。基本上,您将发布一个带有名称的通知,任何观察该名称通知的类都将调用一个方法并执行其操作。 - Ben Kane