81 lines
1.6 KiB
JavaScript
81 lines
1.6 KiB
JavaScript
var asdf = require("asdf-games");
|
|
const { Texture, TileSprite } = asdf;
|
|
|
|
var texture = new Texture("./res/player.png");
|
|
|
|
class Player extends TileSprite {
|
|
constructor(keys, window) {
|
|
super(texture, 24, 24);
|
|
this.scale = { x: 2, y: 2 };
|
|
|
|
this.window = window;
|
|
|
|
// Rate walking = 0.4
|
|
// Rate running = 0.08
|
|
|
|
this.rate = 1;
|
|
this.direction = 1;
|
|
this.frames = [
|
|
{ x: 0, y: 1 },
|
|
{ x: 1, y: 1 },
|
|
{ x: 2, y: 1 },
|
|
{ x: 3, y: 1 }
|
|
];
|
|
this.curTime = 0;
|
|
this.curFrame = 0;
|
|
this.frame = this.frames[this.curFrame];
|
|
|
|
this.pos.x = (this.window.w / 2) - (24 * this.scale.x / 2);
|
|
this.pos.y = (this.window.h / 2) - (24 * this.scale.y / 2);
|
|
|
|
this.keys = keys;
|
|
}
|
|
|
|
update(dt) {
|
|
const { rate, frames } = this;
|
|
this.curTime += dt;
|
|
|
|
// Change speed
|
|
if (this.keys.x || this.keys.y) {
|
|
// Walking
|
|
this.rate = 0.35;
|
|
} else {
|
|
// Standstill
|
|
this.curFrame = 0;
|
|
}
|
|
if (this.keys.action && (this.keys.x || this.keys.y)) {
|
|
// Running
|
|
this.rate = 0.08;
|
|
}
|
|
|
|
// Change walking direction
|
|
if (this.keys.x == -1) {
|
|
// Left
|
|
this.direction = 3;
|
|
}
|
|
if (this.keys.x == 1) {
|
|
// Right
|
|
this.direction = 2;
|
|
}
|
|
if (this.keys.y == -1) {
|
|
// Down
|
|
this.direction = 0;
|
|
}
|
|
if (this.keys.y == 1) {
|
|
// Up
|
|
this.direction = 1;
|
|
}
|
|
|
|
this.frames.forEach(element => {
|
|
element.y = this.direction;
|
|
});
|
|
|
|
// Animate
|
|
if (this.curTime > rate) {
|
|
this.frame = frames[this.curFrame++ % frames.length];
|
|
this.curTime -= rate;
|
|
}
|
|
}
|
|
}
|
|
|
|
module.exports = Player; |