54 lines
1.8 KiB
TypeScript
54 lines
1.8 KiB
TypeScript
import { PLAYER_EYE_HEIGHT, PLAYER_HEIGHT, PLAYER_WIDTH } from "$/common/constants.ts";
|
|
import type { ClientLevel } from "../level/client_level.ts";
|
|
import type { Texture } from "../renderer/mod.ts";
|
|
import { decode_skin } from "../skins.ts";
|
|
import { Entity } from "./entity.ts";
|
|
|
|
export abstract class Player extends Entity {
|
|
name: string;
|
|
// undefined draws the default skin
|
|
skin: Texture | undefined;
|
|
// 3 pixel wide arms, for skins made for them
|
|
slim = false;
|
|
#skin_version = 0;
|
|
|
|
// how far the limbs have swung and how hard they swing (0 to 1), like minecraft's WalkAnimationState
|
|
walk_position = 0;
|
|
walk_speed = 0;
|
|
prev_walk_speed = 0;
|
|
|
|
constructor(level: ClientLevel, id: string, name: string) {
|
|
super(level, id, PLAYER_WIDTH, PLAYER_HEIGHT, PLAYER_EYE_HEIGHT);
|
|
this.name = name;
|
|
}
|
|
|
|
// a base64 png from the server, or undefined for the default. the old skin stays until the new one is decoded
|
|
async set_skin(skin: string | undefined, slim = false) {
|
|
const version = ++this.#skin_version;
|
|
const texture = skin ? await decode_skin(skin) : undefined;
|
|
if (version !== this.#skin_version) {
|
|
// a newer skin came while this one was decoding
|
|
texture?.tex.destroy();
|
|
return;
|
|
}
|
|
this.skin?.tex.destroy();
|
|
this.skin = texture;
|
|
this.slim = slim;
|
|
}
|
|
|
|
// after moving each tick. full speed is 5 blocks per second, a bit faster than walking
|
|
update_walk_animation() {
|
|
const moved = Math.hypot(this.x - this.prev_x, this.z - this.prev_z);
|
|
this.prev_walk_speed = this.walk_speed;
|
|
this.walk_speed += (Math.min(moved * 4, 1) - this.walk_speed) * 0.4;
|
|
this.walk_position += this.walk_speed;
|
|
}
|
|
|
|
walk_animation(partial_tick: number) {
|
|
return {
|
|
position: this.walk_position - this.walk_speed * (1 - partial_tick),
|
|
speed: this.prev_walk_speed + (this.walk_speed - this.prev_walk_speed) * partial_tick,
|
|
};
|
|
}
|
|
}
|