partey_workadventure/front/src/Phaser/Entity/Character.ts

436 lines
15 KiB
TypeScript
Raw Normal View History

import { PlayerAnimationDirections, PlayerAnimationTypes } from "../Player/Animation";
import { SpeechBubble } from "./SpeechBubble";
import Text = Phaser.GameObjects.Text;
import Container = Phaser.GameObjects.Container;
import Sprite = Phaser.GameObjects.Sprite;
2021-11-09 18:10:55 +01:00
import DOMElement = Phaser.GameObjects.DOMElement;
import { TextureError } from "../../Exception/TextureError";
import { Companion } from "../Companion/Companion";
import type { GameScene } from "../Game/GameScene";
import { DEPTH_INGAME_TEXT_INDEX } from "../Game/DepthIndexes";
import type OutlinePipelinePlugin from "phaser3-rex-plugins/plugins/outlinepipeline-plugin.js";
import { isSilentStore } from "../../Stores/MediaStore";
2021-12-04 16:29:28 +01:00
import { lazyLoadPlayerCharacterTextures, loadAllDefaultModels } from "./PlayerTexturesLoadingManager";
import { TexturesHelper } from "../Helpers/TexturesHelper";
import type { PictureStore } from "../../Stores/PictureStore";
import { Unsubscriber, Writable, writable } from "svelte/store";
import { createColorStore } from "../../Stores/OutlineColorStore";
2022-01-26 14:59:23 +01:00
import type { OutlineableInterface } from '../Game/OutlineableInterface';
import type { OutlineConfig } from '../../Utils/OutlineManager';
const playerNameY = -25;
2020-06-04 18:54:34 +02:00
interface AnimationData {
key: string;
frameRate: number;
repeat: number;
frameModel: string; //todo use an enum
frames: number[];
2020-06-04 18:54:34 +02:00
}
2021-05-19 18:08:53 +02:00
const interactiveRadius = 35;
2021-05-10 17:10:41 +02:00
2022-01-26 14:59:23 +01:00
export abstract class Character extends Container implements OutlineableInterface {
private bubble: SpeechBubble | null = null;
2022-01-26 10:54:51 +01:00
private readonly playerNameText: Text;
public playerName: string;
public sprites: Map<string, Sprite>;
protected lastDirection: PlayerAnimationDirections = PlayerAnimationDirections.Down;
2020-10-12 11:22:41 +02:00
//private teleportation: Sprite;
private invisible: boolean;
2021-04-01 18:51:51 +02:00
public companion?: Companion;
2021-11-09 18:10:55 +01:00
private emote: Phaser.GameObjects.DOMElement | null = null;
private emoteTween: Phaser.Tweens.Tween | null = null;
scene: GameScene;
private readonly _pictureStore: Writable<string | undefined>;
private readonly outlineColorStore = createColorStore();
private readonly outlineColorStoreUnsubscribe: Unsubscriber;
constructor(
scene: GameScene,
x: number,
y: number,
texturesPromise: Promise<string[]>,
name: string,
direction: PlayerAnimationDirections,
moving: boolean,
frame: string | number,
isClickable: boolean,
companion: string | null,
companionTexturePromise?: Promise<string>
2020-06-04 18:54:34 +02:00
) {
super(scene, x, y /*, texture, frame*/);
this.scene = scene;
2022-01-26 10:54:51 +01:00
this.playerName = name;
this.invisible = true;
this.sprites = new Map<string, Sprite>();
this._pictureStore = writable(undefined);
//textures are inside a Promise in case they need to be lazyloaded before use.
texturesPromise
.then((textures) => {
this.addTextures(textures, frame);
this.invisible = false;
this.playAnimation(direction, moving);
return this.getSnapshot().then((htmlImageElementSrc) => {
this._pictureStore.set(htmlImageElementSrc);
});
})
.catch(() => {
return lazyLoadPlayerCharacterTextures(scene.load, ["color_22", "eyes_23"]).then((textures) => {
this.addTextures(textures, frame);
this.invisible = false;
this.playAnimation(direction, moving);
});
});
2022-01-26 10:54:51 +01:00
this.playerNameText = new Text(scene, 0, playerNameY, name, {
fontFamily: '"Press Start 2P"',
fontSize: "8px",
strokeThickness: 2,
stroke: "gray",
metrics: {
ascent: 20,
descent: 10,
fontSize: 35,
},
});
2022-01-26 10:54:51 +01:00
this.playerNameText.setOrigin(0.5).setDepth(DEPTH_INGAME_TEXT_INDEX);
this.add(this.playerNameText);
if (isClickable) {
2021-05-10 17:10:41 +02:00
this.setInteractive({
hitArea: new Phaser.Geom.Circle(0, 0, interactiveRadius),
hitAreaCallback: Phaser.Geom.Circle.Contains, //eslint-disable-line @typescript-eslint/unbound-method
useHandCursor: true,
});
}
this.outlineColorStoreUnsubscribe = this.outlineColorStore.subscribe((color) => {
if (color === undefined) {
2022-01-26 10:54:51 +01:00
this.getOutlinePlugin()?.remove(this.playerNameText);
} else {
2022-01-26 10:54:51 +01:00
this.getOutlinePlugin()?.remove(this.playerNameText);
this.getOutlinePlugin()?.add(this.playerNameText, {
thickness: 2,
outlineColor: color,
});
}
this.scene.markDirty();
});
scene.add.existing(this);
this.scene.physics.world.enableBody(this);
this.getBody().setImmovable(true);
this.getBody().setCollideWorldBounds(true);
this.setSize(16, 16);
this.getBody().setSize(16, 16); //edit the hitbox to better match the character model
this.getBody().setOffset(0, 8);
2021-10-14 17:32:27 +02:00
this.setDepth(0);
if (typeof companion === "string") {
2021-05-10 17:10:41 +02:00
this.addCompanion(companion, companionTexturePromise);
}
2021-04-01 18:51:51 +02:00
}
2022-01-26 12:57:10 +01:00
public getPosition(): { x: number, y: number } {
return { x: this.x, y: this.y };
}
2022-01-26 14:59:23 +01:00
public getOutlineConfig(): OutlineConfig {
return {
thickness: 2,
outlineColor: 0xffff00,
}
}
public getObjectToOutline(): Phaser.GameObjects.GameObject {
return this.playerNameText;
}
private async getSnapshot(): Promise<string> {
const sprites = Array.from(this.sprites.values()).map((sprite) => {
return { sprite, frame: 1 };
});
return TexturesHelper.getSnapshot(this.scene, ...sprites).catch((reason) => {
console.warn(reason);
2021-12-04 16:29:28 +01:00
for (const sprite of this.sprites.values()) {
// we can be sure that either predefined woka or body texture is at this point loaded
if (sprite.texture.key.includes("color") || sprite.texture.key.includes("male")) {
return this.scene.textures.getBase64(sprite.texture.key);
}
}
return "male1";
2021-11-29 20:39:09 +01:00
});
}
public addCompanion(name: string, texturePromise?: Promise<string>): void {
if (typeof texturePromise !== "undefined") {
this.companion = new Companion(this.scene, this.x, this.y, name, texturePromise);
}
2020-06-04 18:54:34 +02:00
}
2020-10-20 16:39:23 +02:00
public addTextures(textures: string[], frame?: string | number): void {
if (textures.length < 1) {
throw new TextureError("no texture given");
}
2020-10-20 16:39:23 +02:00
for (const texture of textures) {
if (this.scene && !this.scene.textures.exists(texture)) {
throw new TextureError("texture not found");
2020-12-18 14:30:46 +01:00
}
2020-10-20 16:39:23 +02:00
const sprite = new Sprite(this.scene, 0, 0, texture, frame);
this.add(sprite);
this.getPlayerAnimations(texture).forEach((d) => {
2020-10-20 16:39:23 +02:00
this.scene.anims.create({
key: d.key,
frames: this.scene.anims.generateFrameNumbers(d.frameModel, { frames: d.frames }),
2020-10-20 16:39:23 +02:00
frameRate: d.frameRate,
repeat: d.repeat,
2020-10-20 16:39:23 +02:00
});
});
2020-10-20 16:39:23 +02:00
// Needed, otherwise, animations are not handled correctly.
if (this.scene) {
this.scene.sys.updateList.add(sprite);
}
2020-10-20 16:39:23 +02:00
this.sprites.set(texture, sprite);
}
}
private getOutlinePlugin(): OutlinePipelinePlugin | undefined {
return this.scene.plugins.get("rexOutlinePipeline") as unknown as OutlinePipelinePlugin | undefined;
}
2020-06-04 18:54:34 +02:00
private getPlayerAnimations(name: string): AnimationData[] {
return [
{
key: `${name}-${PlayerAnimationDirections.Down}-${PlayerAnimationTypes.Walk}`,
frameModel: name,
frames: [0, 1, 2, 1],
frameRate: 10,
repeat: -1,
},
{
key: `${name}-${PlayerAnimationDirections.Left}-${PlayerAnimationTypes.Walk}`,
frameModel: name,
frames: [3, 4, 5, 4],
frameRate: 10,
repeat: -1,
},
{
key: `${name}-${PlayerAnimationDirections.Right}-${PlayerAnimationTypes.Walk}`,
frameModel: name,
frames: [6, 7, 8, 7],
frameRate: 10,
repeat: -1,
},
{
key: `${name}-${PlayerAnimationDirections.Up}-${PlayerAnimationTypes.Walk}`,
frameModel: name,
frames: [9, 10, 11, 10],
frameRate: 10,
repeat: -1,
},
{
key: `${name}-${PlayerAnimationDirections.Down}-${PlayerAnimationTypes.Idle}`,
frameModel: name,
frames: [1],
frameRate: 10,
repeat: 1,
},
{
key: `${name}-${PlayerAnimationDirections.Left}-${PlayerAnimationTypes.Idle}`,
frameModel: name,
frames: [4],
frameRate: 10,
repeat: 1,
},
{
key: `${name}-${PlayerAnimationDirections.Right}-${PlayerAnimationTypes.Idle}`,
frameModel: name,
frames: [7],
frameRate: 10,
repeat: 1,
},
{
key: `${name}-${PlayerAnimationDirections.Up}-${PlayerAnimationTypes.Idle}`,
frameModel: name,
frames: [10],
frameRate: 10,
repeat: 1,
},
];
2020-06-04 18:54:34 +02:00
}
protected playAnimation(direction: PlayerAnimationDirections, moving: boolean): void {
if (this.invisible) return;
for (const [texture, sprite] of this.sprites.entries()) {
if (!sprite.anims) {
console.error("ANIMS IS NOT DEFINED!!!");
return;
}
if (moving && (!sprite.anims.currentAnim || sprite.anims.currentAnim.key !== direction)) {
sprite.play(texture + "-" + direction + "-" + PlayerAnimationTypes.Walk, true);
} else if (!moving) {
sprite.anims.play(texture + "-" + direction + "-" + PlayerAnimationTypes.Idle, true);
}
}
}
protected getBody(): Phaser.Physics.Arcade.Body {
const body = this.body;
if (!(body instanceof Phaser.Physics.Arcade.Body)) {
throw new Error("Container does not have arcade body");
2020-06-04 18:54:34 +02:00
}
return body;
}
move(x: number, y: number) {
const body = this.getBody();
body.setVelocity(x, y);
if (Math.abs(body.velocity.x) > Math.abs(body.velocity.y)) {
if (body.velocity.x < 0) {
this.lastDirection = PlayerAnimationDirections.Left;
} else if (body.velocity.x > 0) {
this.lastDirection = PlayerAnimationDirections.Right;
}
} else {
if (body.velocity.y < 0) {
this.lastDirection = PlayerAnimationDirections.Up;
} else if (body.velocity.y > 0) {
this.lastDirection = PlayerAnimationDirections.Down;
}
2020-04-13 15:15:20 +02:00
}
this.playAnimation(this.lastDirection, true);
this.setDepth(this.y);
2021-04-01 18:51:51 +02:00
if (this.companion) {
this.companion.setTarget(this.x, this.y, this.lastDirection);
}
}
stop() {
this.getBody().setVelocity(0, 0);
this.playAnimation(this.lastDirection, false);
2020-04-13 15:41:11 +02:00
}
2020-04-27 18:12:36 +02:00
2020-04-12 19:35:51 +02:00
say(text: string) {
if (this.bubble) return;
this.bubble = new SpeechBubble(this.scene, this, text);
2020-04-12 19:35:51 +02:00
setTimeout(() => {
2020-06-04 18:11:07 +02:00
if (this.bubble !== null) {
this.bubble.destroy();
this.bubble = null;
}
}, 3000);
2020-04-12 19:35:51 +02:00
}
destroy(): void {
for (const sprite of this.sprites.values()) {
if (this.scene) {
this.scene.sys.updateList.remove(sprite);
}
}
this.list.forEach((objectContaining) => objectContaining.destroy());
this.outlineColorStoreUnsubscribe();
super.destroy();
}
2021-09-10 16:57:21 +02:00
isSilent() {
isSilentStore.set(true);
}
noSilent() {
isSilentStore.set(false);
}
2021-06-29 08:37:01 +02:00
playEmote(emote: string) {
2021-05-10 17:10:41 +02:00
this.cancelPreviousEmote();
2021-09-10 16:57:21 +02:00
const emoteY = -45;
2021-11-09 18:10:55 +01:00
const image = new Image(16, 16);
image.src = emote;
this.emote = new DOMElement(this.scene, -1, 0, image, "z-index:10;");
this.emote.setAlpha(0);
this.add(this.emote);
2021-09-10 16:57:21 +02:00
this.createStartTransition(emoteY);
}
2021-09-10 16:57:21 +02:00
private createStartTransition(emoteY: number) {
this.emoteTween = this.scene?.tweens.add({
targets: this.emote,
props: {
alpha: 1,
y: emoteY,
},
ease: "Power2",
duration: 500,
onComplete: () => {
2021-09-10 16:57:21 +02:00
this.startPulseTransition(emoteY);
},
});
}
2021-09-10 16:57:21 +02:00
private startPulseTransition(emoteY: number) {
if (this.emote) {
this.emoteTween = this.scene?.tweens.add({
targets: this.emote,
props: {
y: emoteY * 1.3,
scale: this.emote.scale * 1.1,
},
duration: 250,
yoyo: true,
repeat: 1,
completeDelay: 200,
onComplete: () => {
this.startExitTransition(emoteY);
},
});
}
}
private startExitTransition(emoteY: number) {
this.emoteTween = this.scene?.tweens.add({
targets: this.emote,
props: {
alpha: 0,
y: 2 * emoteY,
},
ease: "Power2",
duration: 500,
onComplete: () => {
this.destroyEmote();
},
});
}
2021-05-10 17:10:41 +02:00
cancelPreviousEmote() {
if (!this.emote) return;
this.emoteTween?.remove();
this.destroyEmote();
}
private destroyEmote() {
2021-05-10 17:10:41 +02:00
this.emote?.destroy();
this.emote = null;
2022-01-26 10:54:51 +01:00
this.playerNameText.setVisible(true);
2021-05-10 17:10:41 +02:00
}
public get pictureStore(): PictureStore {
return this._pictureStore;
}
public setOutlineColor(color: number): void {
this.outlineColorStore.setColor(color);
}
public removeOutlineColor(): void {
this.outlineColorStore.removeColor();
}
2020-04-27 18:12:36 +02:00
}