如何在Swift中获得按下

如何在Swift中获得按下

本文介绍了如何在Swift中获得按下的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试学习Swift语言,并且在YouTube上关注了很多教程.由于它们大多数用于iOS,因此我想制作该OSX的OSX版本: https://www.youtube.com/watch?v=8PrVHrs10to (SideScroller游戏)

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)

我认真地遵循了它,但是当我不得不更新播放器位置时,我被困在大约22分钟的视频中.我的第一个问题是按下按键.我来自C#语言,所以我想找到类似

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")
    }
}

我通过使用println(theEvent.keyCode)找到了对应的值(123/124/126),但是如果我不得不识别很多键的话,它并不是很有用.无论如何,它适用于本游戏,玩家的位置也会改变.但是我还有另一个问题,那就是每次更新时似乎都不会调用keyDown函数(因此每秒60次),这会阻止播放器平稳移动.

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.

所以,这是我的问题:如何在每次更新时调用 keyDown ,还有谁有更干净的方法来获取按下的键?

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 ?

谢谢

推荐答案

好吧,我找到了更新的方法,所以将其发布在这里,因为它可能会对其他人有所帮助.这个想法是使用一个布尔值:

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...

这篇关于如何在Swift中获得按下的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 12:11