import { PlayerContext } from "./PlayerContext"; import { IPlayerState } from "./IPlayerState"; import { PlayerStateType } from "./PlayerStateType"; export class PlayerStateMachine { private activeState: IPlayerState; private currentStateType: PlayerStateType; private readonly states: Map; constructor( private readonly context: PlayerContext, states: Map, initialState: PlayerStateType = PlayerStateType.Idle, ) { this.states = states; this.activeState = states.get(initialState)!; this.currentStateType = initialState; this.activeState.enter(this.context); } get currentState(): PlayerStateType { return this.currentStateType; } setState(stateType: PlayerStateType) { if (this.currentStateType === stateType) return; // console.log(`[PlayerState] ${this.currentStateType} -> ${stateType}`); this.activeState.exit(this.context); this.activeState = this.states.get(stateType)!; this.currentStateType = stateType; this.activeState.enter(this.context); } update(deltaTime: number) { this.activeState.update(this.context, deltaTime); } }