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.

TKeyboardController.js 1.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import {Trait} from "../Entity.js";
  2. export default class TKeyboardController extends Trait {
  3. constructor(entity) {
  4. super(entity, "keyboardController", [ "physics" ]);
  5. this.speed = 50;
  6. this.speedAir = 20;
  7. this.jump = 8;
  8. this.jumpTimeMax = 0.4;
  9. this.updrift = 100;
  10. this.map = {
  11. KeyA: 'left',
  12. KeyD: 'right',
  13. Space: "jump",
  14. };
  15. this.pressed = {};
  16. this.jumpTime = 0;
  17. this.jumping = false;
  18. }
  19. onkey(evt) {
  20. let name = this.map[evt.code];
  21. if (name == null) return;
  22. evt.preventDefault();
  23. this.pressed[name] = evt.type === 'keydown';
  24. }
  25. init() {
  26. window.addEventListener("keydown", e => this.onkey(e));
  27. window.addEventListener("keyup", e => this.onkey(e));
  28. }
  29. update(dt) {
  30. let phys = this.entity.t.physics;
  31. let speed = phys.onGround ? this.speed : this.speedAir;
  32. if (this.pressed.left)
  33. phys.velocity.x -= speed * dt;
  34. if (this.pressed.right)
  35. phys.velocity.x += speed * dt;
  36. if (phys.onGround && this.pressed.jump) {
  37. phys.velocity.y = -this.jump;
  38. console.log("jumping to", phys.velocity.y);
  39. this.jumpTime = this.jumpTimeMax;
  40. this.jumping = true;
  41. phys.onGround = false;
  42. }
  43. if (phys.onGround || !this.pressed.jump || this.jumpTime <= 0)
  44. this.jumping = false;
  45. if (this.jumping) {
  46. phys.velocity.y -= this.updrift * this.jumpTime * dt;
  47. this.jumpTime -= dt;
  48. }
  49. }
  50. }