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

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