caa-game/src/entities/player.js

114 lines
3.0 KiB
JavaScript

var asdf = require("asdf-games");
const { Texture, TileSprite, AnimManager, wallslide } = asdf;
const texture = new Texture("../res/images/player.png");
class Player extends TileSprite {
constructor(keys, window) {
super(texture, 24, 24);
this.scale = { x: 2, y: 2 };
this.window = window;
this.keys = keys;
this.rate = {
walking: 0.2,
running: 0.1
};
this.speed = {
walking: 75,
running: 150
};
this.anims = new AnimManager(this);
// North
this.anims.add("walk_n", [0, 1, 2, 3].map(x => ({ x, y: 0 })), this.rate.walking);
this.anims.add("run_n", [0, 1, 2, 3].map(x => ({ x, y: 0 })), this.rate.running);
// East
this.anims.add("walk_e", [0, 1, 2, 3].map(x => ({ x, y: 2 })), this.rate.walking);
this.anims.add("run_e", [0, 1, 2, 3].map(x => ({ x, y: 2 })), this.rate.running);
// South
this.anims.add("walk_s", [0, 1, 2, 3].map(x => ({ x, y: 1 })), this.rate.walking);
this.anims.add("run_s", [0, 1, 2, 3].map(x => ({ x, y: 1 })), this.rate.running);
// West
this.anims.add("walk_w", [0, 1, 2, 3].map(x => ({ x, y: 3 })), this.rate.walking);
this.anims.add("run_w", [0, 1, 2, 3].map(x => ({ x, y: 3 })), this.rate.running);
this.anims.play("walk_s");
this.lives = 5;
this.items = {
keys: [ ],
repellant: false
};
this.stamina = {
current: 5,
max: 5
};
this.refocus = false;
this.hitBox = {
x: 4,
y: 0,
w: 30,
h: 48
};
}
update(dt) {
super.update(dt);
// Animate
if (this.keys.x == -1) {
// Left
(this.keys.ctrl && !(this.stamina.current <= 0)) ?
this.anims.play("run_w") : this.anims.play("walk_w");
} else if (this.keys.x == 1) {
// Right
(this.keys.ctrl && !(this.stamina.current <= 0)) ?
this.anims.play("run_e") : this.anims.play("walk_e");
} else if (this.keys.y == -1) {
// Up
(this.keys.ctrl && !(this.stamina.current <= 0)) ?
this.anims.play("run_n") : this.anims.play("walk_n");
} else if (this.keys.y == 1) {
// Down
(this.keys.ctrl && !(this.stamina.current <= 0)) ?
this.anims.play("run_s") : this.anims.play("walk_s");
} else {
// Idle
this.anims.stop();
}
// Lose stamina
if (this.keys.ctrl) {
if (!(this.stamina.current <= 0)) {
this.stamina.current -= dt;
} else {
this.stamina.current = 0;
}
} else {
if (!(this.stamina.current >= this.stamina.max)) {
this.stamina.current += dt;
} else {
this.stamina.current = this.stamina.max;
}
}
// Speed
const xo = this.keys.x * ((this.keys.ctrl && !(this.stamina.current <= 0)) ?
this.speed.running : this.speed.walking) * dt;
const yo = this.keys.y * ((this.keys.ctrl && !(this.stamina.current <= 0)) ?
this.speed.running : this.speed.walking) * dt;
// Move
const r = wallslide.wallslide(this, this.level, xo, yo);
this.pos.x += r.x;
this.pos.y += r.y;
}
}
module.exports = Player;