How to disable key bindings in X3DOM

294 Views Asked by At

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?

2

There are 2 best solutions below

1
On

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();
        //
        // ...
        //
    }
});
0
On

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" ...>