3

I am using X3DOM for a simple game, but I can't use keyboard keys the way I want to, because X3DOM reacts to them.

Example:

window.addEventListener('keydown', event => this.onKeyDown(event));

I want to have my own key event for if keyCode == 68. That works, but X3DOM reacts to it too, by changing the navigation mode and displaying an overlay.

How can I disable this?

tukan
  • 17,050
  • 1
  • 20
  • 48
Gem
  • 53
  • 5

2 Answers2

2

disclaimer: I've never used x3dom, I was just poking around in the source code

there appears to be some code which disables keypress handling

this.disableKeys = x3dElem.getAttribute("keysEnabled");
this.disableKeys = this.disableKeys ? (this.disableKeys.toLowerCase() == "true") : false;

which is later read when setting up the keypress event handler:

this.onKeyPress = function (evt) {
    if (!this.parent.disableKeys) {
        evt.preventDefault();
        this.parent.doc.onKeyPress(evt.charCode);
    }
    this.parent.doc.needRender = true;
}

So it appears setting keysEnabled=... attribute can turn this off. The oddity appears to be that their logic is backwards (?) for the condition:

  • x3dElem.getAttribute("keysEnabled") must be truthy (that is, it must have an attribute)
  • if that is falsey, this.disableKeys is always false
  • otherwise it is equal to that attribute's value lower-cased being equal to 'true'

So to disable keypress events, use <... keysEnabled="true" ...>

I made a github issue about the backwards logic, perhaps in the future it will be keysDisabled="true" instead

update:

in the latest version the attribute has been renamed to disableKeys so use <... disableKeys="true" ...>

anthony sottile
  • 61,815
  • 15
  • 148
  • 207
1

You can use event.preventDefault to prevent X3DOM from reacting to that key:

window.addEventListener('keydown', event => {
    if ((event.which === 68) || (event.keyCode === 68)){
        event.preventDefault();
        //
        // ...
        //
    }
});
wildpeaks
  • 7,273
  • 2
  • 30
  • 35
  • this only works if you're able to hook into this before loading x3dom -- otherwise due to event handler ordering this is too late – anthony sottile Feb 04 '19 at 17:14