|
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374 |
- 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.jumpLeeway = 0.4;
-
- this.map = {
- KeyA: 'left',
- KeyD: 'right',
- 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;
-
- let canJump =
- !this.jumped && onGround &&
- this.entity.time -phys.timeLastOnGround < this.jumpLeeway;
-
- if (this.pressed.jump && canJump) {
- phys.velocity.y = -this.jump;
- this.entity.bounds.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;
- }
- }
- }
|