I'm writing a game in Spritekit for OSX. How to check if a key is currently being pressed? Consider this example:
//some code. this could be e.g. inside a game loop
if (/*is key 'w' pressed*/) {
// move forward
}
//some more code
Both Swift and Objective-C solutions are useful.
Note: I am not interested in receiving or dealing with the event, so I'd like to avoid that if possible. I only need to check whether a specific key is currently pressed or not.
Note #2: This question is not a duplicate of the linked question, as it only addresses the issue from the perspective of receiving the 'keyPressed' event (as a parameter to a method call), not from the perspective of performing a check elsewhere to find out whether a key is currently being pressed. In other words, it does not help me fill in the condition in the if-statement above.
I'm thinking I may have to end up maintaining an Array of booleans, one for each keycode, and updating its contents as I receive keyDown and keyUp events. But I was hoping for a more elegant solution as this seems pretty trivial functionality.
If it's more convenient to poll instead of receiving notifications, you could use the Quartz Event Services function CGEventSourceKeyState.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With