93 lines
2.3 KiB
TypeScript
Raw Normal View History

2022-12-08 21:14:02 +08:00
import { _decorator, Animation, Component } from "cc";
import { EntityTypeEnum } from "../Common";
import { FsmParamTypeEnum } from "../Enum";
const { ccclass } = _decorator;
import State from "./State";
import SubStateMachine from "./SubStateMachine";
2022-11-27 23:23:47 +08:00
2022-12-08 21:14:02 +08:00
type ParamsValueType = boolean | number;
2022-11-27 23:23:47 +08:00
export interface IParamsValue {
2022-12-08 21:14:02 +08:00
type: FsmParamTypeEnum;
value: ParamsValueType;
2022-11-27 23:23:47 +08:00
}
export const getInitParamsTrigger = () => {
return {
type: FsmParamTypeEnum.Trigger,
value: false,
2022-12-08 21:14:02 +08:00
};
};
2022-11-27 23:23:47 +08:00
export const getInitParamsNumber = () => {
return {
type: FsmParamTypeEnum.Number,
value: 0,
2022-12-08 21:14:02 +08:00
};
};
2022-11-27 23:23:47 +08:00
/***
*
* 1.entity的state或者direction改变触发setter
* 2.setter里触发fsm的setParams方法
* 3.setParams执行run方法run方法由子类重写
* 4.run方法会更改currentStatecurrentState的setter
* 5-1.currentState是子状态机run方法run方法又会设置子状态机的currentStaterun方法
* 5-2.run方法就是播放动画
*/
/***
*
*/
2022-12-08 21:14:02 +08:00
@ccclass("StateMachine")
2022-11-27 23:23:47 +08:00
export default abstract class StateMachine extends Component {
2022-12-08 21:14:02 +08:00
private _currentState: State | SubStateMachine = null;
params: Map<string, IParamsValue> = new Map();
stateMachines: Map<string, SubStateMachine | State> = new Map();
animationComponent: Animation;
type: EntityTypeEnum;
2022-11-27 23:23:47 +08:00
getParams(paramName: string) {
if (this.params.has(paramName)) {
2022-12-08 21:14:02 +08:00
return this.params.get(paramName).value;
2022-11-27 23:23:47 +08:00
}
}
setParams(paramName: string, value: ParamsValueType) {
if (this.params.has(paramName)) {
2022-12-08 21:14:02 +08:00
this.params.get(paramName).value = value;
this.run();
this.resetTrigger();
2022-11-27 23:23:47 +08:00
}
}
get currentState() {
2022-12-08 21:14:02 +08:00
return this._currentState;
2022-11-27 23:23:47 +08:00
}
set currentState(newState) {
if (!newState) {
2022-12-08 21:14:02 +08:00
return;
2022-11-27 23:23:47 +08:00
}
2022-12-08 21:14:02 +08:00
this._currentState = newState;
this._currentState.run();
2022-11-27 23:23:47 +08:00
}
/***
2022-12-08 21:14:02 +08:00
* trigger
*/
2022-11-27 23:23:47 +08:00
resetTrigger() {
for (const [, value] of this.params) {
if (value.type === FsmParamTypeEnum.Trigger) {
2022-12-08 21:14:02 +08:00
value.value = false;
2022-11-27 23:23:47 +08:00
}
}
}
/***
* currentState
*/
2022-12-08 21:14:02 +08:00
abstract init(...args: any[]): void;
abstract run(): void;
2022-11-27 23:23:47 +08:00
}