0

Note: This is for SpriteKit using Objective C.

I have a single scene called GameScene in my game and I'm using a GKStateMachine to handle the various states Play, Pause and ReadyToPlay. I know you can handle all of the key presses in the keyDown: method of GameScene, but it can get very messy very quickly with all of the different conditions and key combinations.

Question: Is there a way to handle the key presses in each of the various state classes instead?

I've read an article that have said NSNotificationCenter is a horrible option. I don't know enough about this stuff to make an informed decision.

Knight0fDragon
  • 16,609
  • 2
  • 23
  • 44
02fentym
  • 1,762
  • 2
  • 16
  • 29

1 Answers1

0

Answer: you can redirect the processing of key pressing to your states, but this is not the correct way. You should determine which key (or key combination) has been pressed and switch the state machine to the corresponding state.

Actually it's quite simple to detect witch key was pressed. You need two properties from NSEvent- modifierFlags and keyCode. Here is example which prints to the console some key combinations:

override func keyDown(with event: NSEvent) {

    let modifierKeys = event.modifierFlags.intersection(NSEvent.ModifierFlags.deviceIndependentFlagsMask)

        switch event.keyCode {
        case 0x31: print("spacebar")
        case 0x33: print("delete")
        case 0x1D: modifierKeys == NSEvent.ModifierFlags.command ? print("CMD + 0") : print("0")
        default: print("any other key")
        }
}

more info about available key codes you can find for example here: Where can I find a list of Mac virtual key codes?

Max Gribov
  • 388
  • 2
  • 7
  • Well, how do you redirect the processing to a state? `currentState` on the GKStateMachine doesn't give the actual class currently active. Isn't it also quite common to capture touch anywhere in a scene? I don't want to switch states, I want to e.g. move a node *if* I'm in a certain state. How would one accomplish testing that? – jeanmartin Jul 24 '21 at 15:21