You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

KeyboardControls.js 690B

12345678910111213141516171819202122232425262728293031323334
  1. import {Trait} from '../Entity';
  2. export default class KeyboardControls extends Trait {
  3. constructor(entity) {
  4. super(entity, "keyboardControls");
  5. this.speed = 500;
  6. this.map = {
  7. KeyA: 'left',
  8. KeyD: 'right',
  9. };
  10. this.pressed = {};
  11. }
  12. onkey(evt) {
  13. let name = this.map[evt.code];
  14. if (name == null) return;
  15. evt.preventDefault();
  16. this.pressed[name] = evt.type === 'keydown';
  17. }
  18. init() {
  19. window.addEventListener("keydown", e => this.onkey(e));
  20. window.addEventListener("keyup", e => this.onkey(e));
  21. }
  22. update(dt) {
  23. if (this.pressed.left)
  24. this.entity.velocity.x -= this.speed * dt;
  25. if (this.pressed.right)
  26. this.entity.velocity.x += this.speed * dt;
  27. }
  28. }