How to get keystrokes in Swift

I am trying to learn the Swift language and I have followed a lot of tutorials on Youtube. Since most of them are for iOS, I wanted to make an OSX version of this: https://www.youtube.com/watch?v=8PrVHrs10to (SideScroller game)

I watched him closely, but I was stuck for about 22 minutes of the video when I need to update the player’s position. My first problem was getting the keys pressed. I came from C #, so I wanted to find something like

If(Keyboard.GetState().IsKeyDown(Keys.Right)) man.Position.x += 5 //player position 

but this does not exist, so I figured it out:

 override func keyDown(theEvent: NSEvent!) { updateManPosition(theEvent) } func updateManPosition(theEvent:NSEvent) { if theEvent.keyCode == 123 { man.position.x -= 2 } else if theEvent.keyCode == 124 { man.position.x += 2 } else if theEvent.keyCode == 126 { println("jump") } } 

I found the corresponding value (123/124/126) using println(theEvent.keyCode) , but this is not very useful if I need to recognize many keys. In any case, he works for this game, the position of the player changes. But I have one more problem, which is that the keyDown function does not seem to be called on every update (60 times per second), which prevents the player from moving smoothly.

SO, here is my question: How can I call keyDown on every update, and does anyone have a cleaner way to get the keys pressed?

thanks

+7
swift keyboard keyboard-events sprite-kit macos
source share
2 answers

Ok, I found how to update, so I post it here because it can help others. The idea is to use a boolean:

 var manIsMoving:Bool = false override func keyDown(theEvent: NSEvent!) // A key is pressed { if theEvent.keyCode == 123 { direction = "left" //get the pressed key } else if theEvent.keyCode == 124 { direction = "right" //get the pressed key } else if theEvent.keyCode == 126 { println("jump") } manIsMoving = true //setting the boolean to true } override func keyUp(theEvent: NSEvent!) { manIsMoving = false } override func update(currentTime: CFTimeInterval) { if manIsMoving { updateManPosition(direction) } else { cancelMovement() } } 

It may help others. But getting pressed key characters remains unclear ...

+3
source share

In combination with the method described above, I created a key change method for a character:

 private func returnChar(theEvent: NSEvent) -> Character?{ let s: String = theEvent.characters! for char in s{ return char } return nil } 

This will return the character (from a keystroke). Then you can do something like this:

 override func keyUp(theEvent: NSEvent) { let s: String = String(self.returnChar(theEvent)!) switch(s){ case "w": println("w") break case "s": println("s") break case "d": println("d") break case "a": println("a") break default: println("default") } } 

You can combine this method and the method on top to create something like a key listener.

+1
source share

All Articles