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.45; this.updrift = 100; this.jumpLeeway = 0.1; this.map = { KeyA: 'left', KeyD: 'right', KeyW: 'up', KeyS: 'down', Space: "jump", }; this.pressed = {}; this.jumpTime = 0; this.jumping = false; this.jumped = 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 onGround = phys.onGround; 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 (this.pressed.down) phys.velocity.y += speed * dt; if (this.pressed.up) phys.velocity.y -= speed * dt; let canJump = !this.jumped && this.entity.time -phys.timeLastOnGround < this.jumpLeeway; if (this.pressed.jump && canJump) { phys.velocity.y -= this.jump; this.entity.pos.y += phys.velocity.y * dt; this.jumpTime = this.jumpTimeMax; this.jumping = true; this.jumped = true; onGround = false; } if (onGround || !this.pressed.jump || this.jumpTime <= 0) this.jumping = false; if (onGround) this.jumped = false; if (this.jumping) { phys.velocity.y -= this.updrift * this.jumpTime * dt; this.jumpTime -= dt; } } }