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.6KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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.jumpLeeway = 0.4;
  11. this.map = {
  12. KeyA: 'left',
  13. KeyD: 'right',
  14. Space: "jump",
  15. };
  16. this.pressed = {};
  17. this.jumpTime = 0;
  18. this.jumping = false;
  19. this.jumped = false
  20. }
  21. onkey(evt) {
  22. let name = this.map[evt.code];
  23. if (name == null) return;
  24. evt.preventDefault();
  25. this.pressed[name] = evt.type === 'keydown';
  26. }
  27. init() {
  28. window.addEventListener("keydown", e => this.onkey(e));
  29. window.addEventListener("keyup", e => this.onkey(e));
  30. }
  31. update(dt) {
  32. let phys = this.entity.t.physics;
  33. let onGround = phys.onGround;
  34. let speed = phys.onGround ? this.speed : this.speedAir;
  35. if (this.pressed.left)
  36. phys.velocity.x -= speed * dt;
  37. if (this.pressed.right)
  38. phys.velocity.x += speed * dt;
  39. let canJump =
  40. !this.jumped && onGround &&
  41. this.entity.time -phys.timeLastOnGround < this.jumpLeeway;
  42. if (this.pressed.jump && canJump) {
  43. phys.velocity.y = -this.jump;
  44. this.entity.bounds.pos.y += phys.velocity.y * dt;
  45. this.jumpTime = this.jumpTimeMax;
  46. this.jumping = true;
  47. this.jumped = true;
  48. onGround = false;
  49. }
  50. if (onGround || !this.pressed.jump || this.jumpTime <= 0)
  51. this.jumping = false;
  52. if (onGround)
  53. this.jumped = false;
  54. if (this.jumping) {
  55. phys.velocity.y -= this.updrift * this.jumpTime * dt;
  56. this.jumpTime -= dt;
  57. }
  58. }
  59. }