91 lines
2.2 KiB
TypeScript
Raw Normal View History

2022-11-27 23:23:47 +08:00
import { _decorator, Animation, Component, SpriteFrame } from 'cc'
import { FsmParamTypeEnum } from '../Enum'
const { ccclass } = _decorator
import State from './State'
import SubStateMachine from './SubStateMachine'
type ParamsValueType = boolean | number
export interface IParamsValue {
type: FsmParamTypeEnum
value: ParamsValueType
}
export const getInitParamsTrigger = () => {
return {
type: FsmParamTypeEnum.Trigger,
value: false,
}
}
export const getInitParamsNumber = () => {
return {
type: FsmParamTypeEnum.Number,
value: 0,
}
}
/***
*
* 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方法就是播放动画
*/
/***
*
*/
@ccclass('StateMachine')
export default abstract class StateMachine extends Component {
private _currentState: State | SubStateMachine = null
params: Map<string, IParamsValue> = new Map()
stateMachines: Map<string, SubStateMachine | State> = new Map()
animationComponent: Animation
getParams(paramName: string) {
if (this.params.has(paramName)) {
return this.params.get(paramName).value
}
}
setParams(paramName: string, value: ParamsValueType) {
if (this.params.has(paramName)) {
this.params.get(paramName).value = value
this.run()
this.resetTrigger()
}
}
get currentState() {
return this._currentState
}
set currentState(newState) {
if (!newState) {
return
}
this._currentState = newState
this._currentState.run()
}
/***
* trigger
*/
resetTrigger() {
for (const [, value] of this.params) {
if (value.type === FsmParamTypeEnum.Trigger) {
value.value = false
}
}
}
/***
* currentState
*/
abstract init(...args: any[]): void
abstract run(): void
}