-1

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#>)
Louis Couture
  • 72
  • 1
  • 9
  • Events are generally created by the system and given to your app to tell you about such things as key presses and mouse movement. Why do you need to create your own event? And if you're going to create one, why not do it right and include the cursor position, as expected, even if you don't need it yourself? – Caleb Aug 04 '18 at 21:13
  • There are already events for mouse clicks already created but I do not see any event for a key press – Louis Couture Aug 04 '18 at 21:16
  • See "keyDown" in the NSWindow docs. – Hack Saw Aug 04 '18 at 21:21
  • Any responder (i.e. window, view, view controller, etc.) in the responder chain can override `keyDown:` to get key press events (as long as they weren't already handled by someone earlier in the chain). – Caleb Aug 04 '18 at 21:22
  • 2
    In answer to your main question, because it's important to know, please read up on Optionals, and "nil". – Hack Saw Aug 04 '18 at 21:23
  • @LeoDabus Neither, SceneKit and AppKit for MacOS – Louis Couture Aug 04 '18 at 21:40

1 Answers1

1

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

Leo Dabus
  • 229,809
  • 59
  • 489
  • 571