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.relVelocity.x -= speed * dt; if (this.pressed.right) phys.relVelocity.x += speed * dt; if (phys.onGround && this.pressed.jump) { phys.relVelocity.y -= this.jump; 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.relVelocity.y -= this.updrift * this.jumpTime * dt; this.jumpTime -= dt; } } }