微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

objective-c – 如何检测OS X上是否按下了某个键?

我正在使用Spritekit for OSX编写游戏.如何检查当前是否按下了某个键?考虑这个例子:

//some code. this Could be e.g. inside a game loop

if (/*is key 'w' pressed*/) {
    // move forward
}

//some more code

Swift和Objective-C解决方案都很有用.

注意:我对收到或处理此事件不感兴趣,所以如果可能的话我想避免这样做.我只需要检查当前是否按下了特定键.

注意#2:这个问题不是链接问题的重复,因为它只从接收’keypressed’事件(作为方法调用的参数)的角度解决问题,而不是从其他地方执行检查的角度来解决找出当前是否按下了某个键.换句话说,它无助于我填写上面if语句中的条件.

我想我可能不得不最终维护一个布尔数组,每个键代码一个,并在收到keyDown和keyUp事件时更新其内容.但我希望有一个更优雅的解决方案,因为这似乎是非常简单的功能.

解决方法

试试这样:

正如我已经提到的,您需要将addLocalMonitorForEventsMatchingMask添加到游戏场景方法didMovetoView中以获取keyUp和keyDown事件,并将key语句添加到keyCode事件:

import SpriteKit

class GameScene: SKScene {

    let sprite = SKSpriteNode(imageNamed:"Spaceship")

    var keyDownState:[String:Bool] = ["k":false,"j":false]
    var movingLeft  = false
    var movingRight = false

    override func didMovetoView(view: SKView) {

        sprite.position = CGPoint(x: view.scene!.frame.midX,y: view.scene!.frame.midY)
        sprite.setScale(0.5)
        addChild(sprite)

        NSEvent.addLocalMonitorForEventsMatchingMask(.KeyDownMask) { (theEvent) -> NSEvent! in
            print("keyDown event")
            switch theEvent.keyCode {
            case 38:
                print("j is down")
                self.keyDownState["j"] = true
            case 40:
                print("k is down")
                self.keyDownState["k"] = true
            default:
                print("unkNown key")
            }
            print(self.keyDownState.description)
            // j and k are pressed
            if self.keyDownState["j"]! && self.keyDownState["k"]! {
                self.sprite.removeAllActions()
                view.scene?.backgroundColor = NSColor.init(red: 1,green: 1,blue: 0,alpha: 1)
            }
            // j is pressed
            if self.keyDownState["j"]! && !self.keyDownState["k"]! {
                view.scene?.backgroundColor = NSColor.greenColor()
                if !self.movingLeft {
                    self.sprite.removeActionForKey("moveSpriteRight")
                    self.movingRight = false
                    let moveSpriteLeft = SKAction.moveByX(-50,y: 0,duration: 0.1)
                    self.sprite.runAction(SKAction.repeatActionForever(moveSpriteLeft),withKey: "moveSpriteLeft")
                    self.movingLeft = true
                }
            }
            // k is pressed
            if !self.keyDownState["j"]! && self.keyDownState["k"]! {
                view.scene?.backgroundColor = NSColor.redColor()
                if !self.movingRight {
                    self.sprite.removeActionForKey("moveSpriteLeft")
                    self.movingLeft = false
                    let moveSpriteRight = SKAction.moveByX(50,duration: 0.1)
                    self.sprite.runAction(SKAction.repeatActionForever(moveSpriteRight),withKey: "moveSpriteRight")
                    self.movingRight = true
                }
            }
            return theEvent
        }

        NSEvent.addLocalMonitorForEventsMatchingMask(.KeyUpMask) { (theEvent) -> NSEvent! in
            print("keyUp event \(theEvent.keyCode)")
            switch theEvent.keyCode {
            case 38:
                print("j is up")
                self.keyDownState["j"] = false
                self.movingLeft = false
            case 40:
                print("k is up")
                self.keyDownState["k"] = false
                self.movingRight = false

            default:
                print("unkNown key")
            }
            print(self.keyDownState.description)
            if self.keyDownState["j"]! && !self.keyDownState["k"]! {
                view.scene?.backgroundColor = NSColor.greenColor()
                    self.sprite.removeActionForKey("moveSpriteRight")
                    self.movingRight = false
                    let moveSpriteLeft = SKAction.moveByX(-50,withKey: "moveSpriteLeft")
                    self.movingLeft = true

            }
            if !self.keyDownState["j"]! && self.keyDownState["k"]! {
                view.scene?.backgroundColor = NSColor.redColor()
                    self.sprite.removeActionForKey("moveSpriteLeft")
                    self.movingLeft = false
                    let moveSpriteRight = SKAction.moveByX(50,withKey: "moveSpriteRight")
                    self.movingRight = true
            }
            if !self.keyDownState["j"]! && !self.keyDownState["k"]! {
                self.sprite.removeAllActions()
                view.scene?.backgroundColor = NSColor(red: 0.72628,green: 0.726298,blue: 0.726288,alpha: 1)
            }
            return theEvent
        }
    }

    override func mouseDown(theEvent: NSEvent) {
        /* Called when a mouse click occurs */

    }

    override func update(currentTime: CFTimeInterval) {
        /* Called before each frame is rendered */
    }
}

Sample project

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐