SpriteKit 游戏的全局键处理程序

Global key handler for SpriteKit Game

目前我的所有按键代码都在我的各种 SKScene classes 中。我只想在每次按下键时发生一些事情。需要重新触发按键才能再次执行操作。我正在使用布尔数组来跟踪这一点。这可能不是最佳的,但这是我当时的想法。我想创建一个 class 来管理所有这些,但是关键事件方法 keyUp 和 keyDown 是在 SKScene classes 中创建的。是否有一种全局方式来处理按键操作,这样我就不必在游戏的每个场景中都重新创建此代码?

我建议使用单例模式来存储和获取您的密钥。因为您可以从您的 SKScene 访问,而不是随时创建或更新。

http://www.galloway.me.uk/tutorials/singleton-classes/这个单例介绍快速而简短。

您可以子class SKView 并在集中位置执行所有按键处理。这种方法有几个好处:1. 因为所有按键逻辑都在一个 class 中,所以对逻辑的更改是针对 class 而不是在所有场景中进行的,并且 2) 它删除了设备-来自多个场景的特定输入逻辑。例如,如果您决定将应用程序移植到 iOS,您只需将界面从 keyboard/mouse 更改为单个文件中的 touches。

以下是 SKView 的自定义子 class 中按键处理程序的实现。它使用 protocol/delegate 设计模式将按键消息发送到各种场景。委派是对象(在本例中为 class)与其他 class 对象通信的一种便捷方式,协议定义了这种通信将如何进行。

  1. 创建 SKView
  2. 的子class

CustomSKView.h

@protocol KeyPressedDelegate;

@interface CustomSKView : SKView

@property (weak) id <KeyPressedDelegate> delegate;

@end

@protocol KeyPressedDelegate

- (void) upArrowPressed;
- (void) downArrowPressed;

@end

CustomSKView.m

所有的按键处理逻辑都在这里。如何处理按键的详细信息隐藏在作用于按键的代码中。

@implementation CustomSKView:SKView {
    // Add instance variables here
}

// This is called when the view is created.
- (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:
                [self.delegate upArrowPressed];
                break;
            case 125:
                [self.delegate downArrowPressed];
                break;
            default:
                break;
        }
    }
}

@end
  1. 采纳协议

GameScene.h

#import "CustomSKView.h"

@interface GameScene : SKScene <KeyPressedDelegate>

@end
  1. 在所有需要按键信息的场景实现delegate方法

GameScene.m

@implementation GameScene

-(void)didMoveToView:(SKView *)view {
    ((CustomSKView *)view).delegate = self;
}

- (void) upArrowPressed {
    NSLog(@"Up Arrow Pressed");
}
- (void) downArrowPressed {
    NSLog(@"Down Arrow Pressed");
}

@end
  1. 在您的主 .xib 文件中,将 SKView 的 class 设置为自定义 class: