Search code examples
swiftappkitnseventnspoint

How to return an undefined value for NSPoint


I am learning swift and I am trying to make a simple app where I move an object (The default ship) with the keyboard. I am designing an event to represent the left keypress. Since I do not need the mouse to be at a specific place, NSLocation is of no real use to me. The official documentation tells me to return the variable locationInWindow, which is my NSPoint for NSLocation, as undefined.

I am not sure to grasp what they mean by this. I tried to use the _undefined keyword, but then this comes up :

Cannot convert value of type '(@autoclosure () -> String, StaticString, UInt) -> _' to specified type 'NSPoint' (aka 'CGPoint')

Here is my code

        var locationInWindow : NSPoint{
        return _undefined
    }

    let movingLeftEvent = NSEvent.keyEvent(with:NSEvent.EventType.keyDown, location: nil, modifierFlags:[], timestamp: [], windowNumber: 0, context: nil , characters: <#String#>, charactersIgnoringModifiers: <#String#>, isARepeat: false, keyCode: <#UInt16#>)

Solution

  • You just need to addLocalMonitorForEvents to your view controller

    NSEvent.addLocalMonitorForEvents(matching: .keyDown) {
        self.keyDown(with: $0)
        return $0
    }
    

    and implement your custom keyDown method:

    override func keyDown(with event: NSEvent) {
        switch event.keyCode {
        case  123:
            // run left arrow code action
            ship.runAction(
                SCNAction.repeatForever(
                    SCNAction.rotateBy(x: 0, y: -2, z: 0, duration: 1)
                )
            )
        case  124:
            // run right arrow code action
            ship.runAction(
                SCNAction.repeatForever(
                    SCNAction.rotateBy(x: 0, y: 2, z: 0, duration: 1)
                )
            )
        default:
            print("event.keyCode:", event.keyCode)
        }
    }
    

    Sample