123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263 |
- import {Trait} from "../Entity.js";
-
- export default class TKeyboardController extends Trait {
- constructor(entity) {
- super(entity, "keyboardController", [ "physics" ]);
-
- this.speed = 50;
- this.speedAir = 20;
-
- this.jump = 8;
- this.jumpTimeMax = 0.4;
- this.updrift = 100;
-
- this.map = {
- KeyA: 'left',
- KeyD: 'right',
- Space: "jump",
- };
-
- this.pressed = {};
-
- this.jumpTime = 0;
- this.jumping = false;
- }
-
- onkey(evt) {
- let name = this.map[evt.code];
- if (name == null) return;
- evt.preventDefault();
- this.pressed[name] = evt.type === 'keydown';
- }
-
- init() {
- window.addEventListener("keydown", e => this.onkey(e));
- window.addEventListener("keyup", e => this.onkey(e));
- }
-
- update(dt) {
- let phys = this.entity.t.physics;
-
- let speed = phys.onGround ? this.speed : this.speedAir;
-
- if (this.pressed.left)
- phys.velocity.x -= speed * dt;
- if (this.pressed.right)
- phys.velocity.x += speed * dt;
- if (phys.onGround && this.pressed.jump) {
- phys.velocity.y = -this.jump;
- console.log("jumping to", phys.velocity.y);
- this.jumpTime = this.jumpTimeMax;
- this.jumping = true;
- phys.onGround = false;
- }
-
- if (phys.onGround || !this.pressed.jump || this.jumpTime <= 0)
- this.jumping = false;
-
- if (this.jumping) {
- phys.velocity.y -= this.updrift * this.jumpTime * dt;
- this.jumpTime -= dt;
- }
- }
- }
|