40 lines
1.2 KiB
TypeScript
40 lines
1.2 KiB
TypeScript
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<PlayerStateType, IPlayerState>;
|
|
|
|
get currentState(): PlayerStateType {
|
|
return this.currentStateType;
|
|
}
|
|
|
|
constructor(
|
|
private readonly context: PlayerContext,
|
|
states: Map<PlayerStateType, IPlayerState>,
|
|
initialState: PlayerStateType = PlayerStateType.Idle,
|
|
) {
|
|
this.states = states;
|
|
this.activeState = states.get(initialState)!;
|
|
this.currentStateType = initialState;
|
|
this.activeState.enter(this.context);
|
|
}
|
|
|
|
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);
|
|
}
|
|
}
|