beartown

Members
  • Content Count

    1
  • Joined

  • Last visited

  1. Hi guys, I've been a web developer for many years now and I want to try something new. I thought of making a JS game and so I'm here! There are a few topics of game development that I'm curious about, so without further ado, I'm about to shoot the first one. I need to shift my thinking patterns towards the game loop, which is different than my everyday's JavaScript. The code will be organised a bit differently. I'm trying to understand how to handle user input in a game. Do you guys use events to handle the input, or maybe some kind of abstraction to check for keyboard state in your game loop? I created a simple class to check if a key (or many keys at the same time) is pressed at the current point of time. I did it by keeping key codes in a Set. Adding them with keydown and removing with keyup. Is this a common practice in JS Game Dev? Here's my class: export default class { constructor() { this.keysPressed = new Set(); this.registerEventListeners(); } registerEventListeners() { window.addEventListener('keydown', this.keyDown.bind(this)); window.addEventListener('keyup', this.keyUp.bind(this)); window.addEventListener('blur', this.clearKeys.bind(this)); } keyDown(event) { if (event.repeat) return; this.keysPressed.add(event.code); } keyUp(event) { this.keysPressed.delete(event.code); } clearKeys() { this.keysPressed.clear(); } isPressed(key) { return this.keysPressed.has(key); } isAnyPressed(keys) { for (const key of keys) { if (this.isPressed(key)) return true; } return false; } areAllPressed(keys) { for (const key of keys) { if (!this.isPressed(key)) return false; } return true; } }