2

I'm trying to create a character movement on the scene in Vue.js.

I've added a key binding to right and left buttons:

  created () {
    window.addEventListener('keyup', this.keyup)
    window.addEventListener('keydown', this.keydown)
  }

and here are the methods:

    keydown (e) {
      if (e.keyCode === 37) this.onWalkLeftPressed()
      if (e.keyCode === 39) this.onWalkRightPressed()
    },

    keyup (e) {
      if (e.keyCode === 37) this.onWalkLeftReleased()
      if (e.keyCode === 39) this.onWalkRightReleased()
    }

When I press and keep my finger on keyboard without releasing it, logically it should instantly start to moving to corresponding direction by increasing or decreasing the "position X" values.

But once I press the button, it fires the first event, then waits for about 500ms, and then continues to firing the other events until I release the button.

Is it some sort of default behaviour of the browser, and do you have any idea how to override it so it keeps firing the event without any delay between the first and the other events ?

Here how it looks:

https://i.stack.imgur.com/3qTKV.jpg

aspirinemaga
  • 3,753
  • 10
  • 52
  • 95

1 Answers1

2

The delay is a default behavior.

So for gaming, you need to use the keydown and keyup events just to implement a key state by yourself. Then with an interval, check every x milliseconds and update the position.

In vue.js the code will be something like this (JSFIDDLE DEMO)

new Vue({
  keys: {}, // this variable should be outside of reactive data
  data: { // Your data here } 
  created () {
    window.addEventListener('keyup', this.keyup);
    window.addEventListener('keydown', this.keydown);
    
    setInterval(this.customKeysChecker, 20);
  },
  methods: {
    keydown (e) {
        this.$options.keys[e.keyCode] = true;
    },
    keyup (e) {
        this.$options.keys[e.keyCode] = false;
    },
    customKeysChecker() {
      const { keys = {} } = this.$options;
      
      if (keys[37]) this.onWalkLeftPressed();
      if (keys[39]) this.onWalkRightPressed();
    },

    onWalkLeftPressed() { //Your code here },
    onWalkRightPressed() { //Your code here }
  }
})

Here you are some helpful links to check:

The.Bear
  • 5,621
  • 2
  • 27
  • 33