How to get the pressed keys in Swift

P1kachu picture P1kachu · Jul 31, 2014 · Viewed 8.1k times · Source

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

I followed it carefully but I am stuck at about 22 minutes of the video when I have to update the player position. My first problem was to get the pressed keys. I come from C# language, so I wanted to find something like

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

but this doesn't exist, so I figured out this:

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) by using println(theEvent.keyCode) but it's not very useful if I have to recognize a lot of keys. Anyway, it works for this game, the position of the player changes. But I have another probem which is that the function keyDown doesn't seem to be called at each update (so 60 times per seconds) which prevent the player to move smoothly.

SO, here is my question: How can I have keyDown called at each update, and does anybody have a cleaner way to get the pressed Keys ?

Thank you

Answer

P1kachu picture P1kachu · Aug 1, 2014

Okay I found how to update, so I post it here 'cause it might 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 the pressed key's characters is still unclear...