DeviceSourceManager KeyUp/KeyDown Event

Quick question, does the DeviceSourceManager have a keyup/keydown event listener or would I need to implement my own solution using addeventlistener? Or, has anyone come up with a solution for keyup/keydown events?

Also I’m surprised no one has asked this.

Hi, and welcome to the forum!

The DSM can provide you with the native keyboard event, if you don’t want to poll on each frame:

dsm.onDeviceConnectedObservable.add((device) => {
  if(device.deviceType === BABYLON.DeviceType.Keyboard) {
    dsm.getDeviceSource(BABYLON.DeviceType.Keyboard).onInputChangedObservable.add((event) => {
        console.log(event);
    })
  }
})

If you want to poll and check, you will need to know the keyCode (arrow up is 38, for example) and then poll on each frame:

if (dsm.getDeviceSource(BABYLON.DeviceType.Keyboard)) {
   if (dsm.getDeviceSource(BABYLON.DeviceType.Keyboard).getInput(38) === 1) {
     // up is pressed
   }
}

I am sure @PolygonalSun can help with further questions about the DSM :slight_smile:

1 Like

Appreciate your reply thank you. The first one works the way I was expecting. I can bind some bool to the current and previous state or something to create a keyup event listener.

Just to point out that you could have used the device object passed into the onDeviceConnectedObservable.add() listener.

dsm.onDeviceConnectedObservable.add((device) => {
  if(device.deviceType === BABYLON.DeviceType.Keyboard) {
    device.onInputChangedObservable.add((event) => {
        console.log(event);
    })
  }
})

And my preliminary code for a keyup event is

let keyup = false

deviceSourceManager.onDeviceConnectedObservable.add((device) => {
  if (device.deviceType === Devices.DeviceType.Keyboard) {
    device.onInputChangedObservable.add((event) => {
      console.log(event)
      console.log('KeyStart: ', keyup)
      if (event.currentState == 0) {
        keyup = true
        console.log('KeyUP: ', keyup)
      } else {
        keyup = false
        console.log('Keydown: ', keyup)
      }
      console.log('KeyEnd: ', keyup)
    })
  }
})

That boolean isn’t necessary, and actually behaves in an odd way lol but it was a good test to see that keyup/down is accurately being tracked. The if statement works perfectly though. Might use a switch or something to call behaviors from somewhere else but this is exactly what I was looking for.

I appreciate your response and your code.

Thanks again.

Edit: Oh just in case someone sees this is confused by why I’m using something called Devices to call the deviceType. I import individual features so this is the import line.

import * as Devices from '@babylonjs/core/DeviceInput'

Thats where I’m getting access to them. Hope that helps a bit more.

2 Likes