Action.ts 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. type Action = { check: () => boolean, entry: () => void, do: (dt: number) => void, dispose: () => void };
  2. export type ActionCreat = (...args: any) => Action;
  3. export default function get_new_action_center(): ActionCenter { return new ActionCenter(); }
  4. /**行为机*/
  5. class ActionCenter {
  6. private _list: Action[] = [];
  7. private _current: Action;
  8. /**加入一个创建行为的闭包的函数
  9. * ActionCreat = (...args: any) => Action;
  10. * Action ={check:() => boolean,entry:() => void,do:(dt:number)=>void}
  11. */
  12. public add(actionCreat: ActionCreat, ...args: any): void {
  13. this._list.push(actionCreat(...args));
  14. }
  15. /**检测和进入行为*/
  16. public check_entry(): void {
  17. if (this._current?.check()) return;
  18. for (let i = 0; i < this._list.length; i++) {
  19. if (this._current != this._list[i] && this._list[i].check()) {
  20. this._current = this._list[i];
  21. this._current.entry();
  22. return;
  23. }
  24. }
  25. this._current = null;
  26. }
  27. /**是否有正在执行的行为 */
  28. public get isAction(): boolean {
  29. return this._current != null;
  30. }
  31. /**执行行为*/
  32. public do(dt: number): void {
  33. if (this._current) this._current.do(dt);
  34. }
  35. /**清除所有行为*/
  36. public clean(): void {
  37. for (let i = 0; i < this._list.length; i++) {
  38. this._list[i].dispose();
  39. }
  40. this._list.length = 0;
  41. this._current = null;
  42. }
  43. /*例子
  44. public test():void{
  45. const who={state:0};
  46. this.add((who:{state:number})=>{
  47. const w = who;
  48. let time:number=0;
  49. return{
  50. check:()=>{
  51. if(w.state==0){
  52. return true;
  53. }
  54. return false;
  55. },
  56. entry:()=>{
  57. time=0;
  58. console.log("entry 行为1",time);
  59. },
  60. do:(dt:number)=>{
  61. time+=dt;
  62. if(time>=2){
  63. console.log("do",time);
  64. w.state=1;
  65. };
  66. }
  67. }
  68. },who);
  69. this.add((who:{state:number})=>{
  70. const w = who;
  71. let time:number=0;
  72. return{
  73. check:()=>{
  74. if(w.state==1){
  75. return true;
  76. }
  77. return false;
  78. },
  79. entry:()=>{
  80. time=0;
  81. console.log("entry 行为2",time);
  82. },
  83. do:(dt:number)=>{
  84. time+=dt;
  85. if(time>=2){
  86. console.log("do",time);
  87. w.state=0;
  88. };
  89. }
  90. }
  91. },who);
  92. }*/
  93. }