Action.ts 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. type Action = {check:() => boolean,entry:() => void,do:(dt:number)=>void,exit:() => void};
  2. export type ActionCreat = (...args: any) => Action;
  3. /**行为机*/
  4. export class ActionMgr {
  5. private _list:Action[]=[];
  6. private _current:Action;
  7. /**加入一个创建行为的闭包的函数
  8. * ActionCreat = (...args: any) => Action;
  9. * Action ={check:() => boolean,entry:() => void,do:(dt:number)=>void}
  10. */
  11. public add(actionCreat:ActionCreat,...args: any):void{
  12. this._list.push(actionCreat(...args));
  13. }
  14. /**检测和进入行为*/
  15. public check_entry():void{
  16. if(this._current?.check()) return;
  17. this._current?.exit()
  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. this._list.length=0;
  38. this._current=null;
  39. }
  40. /*例子
  41. public test():void{
  42. const who={state:0};
  43. this.add((who:{state:number})=>{
  44. const w = who;
  45. let time:number=0;
  46. return{
  47. check:()=>{
  48. if(w.state==0){
  49. return true;
  50. }
  51. return false;
  52. },
  53. entry:()=>{
  54. time=0;
  55. console.log("entry 行为1",time);
  56. },
  57. do:(dt:number)=>{
  58. time+=dt;
  59. if(time>=2){
  60. console.log("do",time);
  61. w.state=1;
  62. };
  63. }
  64. }
  65. },who);
  66. this.add((who:{state:number})=>{
  67. const w = who;
  68. let time:number=0;
  69. return{
  70. check:()=>{
  71. if(w.state==1){
  72. return true;
  73. }
  74. return false;
  75. },
  76. entry:()=>{
  77. time=0;
  78. console.log("entry 行为2",time);
  79. },
  80. do:(dt:number)=>{
  81. time+=dt;
  82. if(time>=2){
  83. console.log("do",time);
  84. w.state=0;
  85. };
  86. }
  87. }
  88. },who);
  89. }*/
  90. }