Bot.ts 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. import Role from "./Role";
  2. const {ccclass, property} = cc._decorator;
  3. @ccclass
  4. export default class Bot extends cc.Component {
  5. role:Role;
  6. target:any;
  7. onLoad(){
  8. this.role = this.node.getComponent(Role);
  9. this.schedule(this.updateOperate,0.5);
  10. }
  11. updateOperate(){
  12. if(this.role.saw.active){//when has saw, target a nearest other role
  13. let distance = 10000;
  14. window.controller.roles.forEach((role:Role)=>{
  15. if(role!=this.role&&role.isValid){
  16. let newDistance = this.role.node.position.sub(role.node.position).mag();
  17. if(newDistance<distance){
  18. distance = newDistance;
  19. this.target = role;
  20. }
  21. }
  22. });
  23. }else{//when without saw, target a nearest saw
  24. let distance = 10000;
  25. window.controller.saws.forEach((saw:cc.Node)=>{
  26. if(saw.isValid){
  27. let newDistance = this.role.node.position.sub(saw.position).mag();
  28. if(newDistance<distance){
  29. distance = newDistance;
  30. this.target = saw;
  31. }
  32. }
  33. });
  34. }
  35. if(!this.target||!this.target.isValid){//when without target, random move
  36. this.randomMove();
  37. }else{//when has target, move to target
  38. this.moveToTarget();
  39. }
  40. }
  41. left(){
  42. this.role.right = false;
  43. this.role.left = true;
  44. }
  45. right(){
  46. this.role.left = false;
  47. this.role.right = true;
  48. }
  49. jump(){
  50. this.role.up = true;
  51. this.scheduleOnce(()=>{
  52. this.role.up = false;
  53. },0.1);
  54. }
  55. randomMove(){
  56. if(Math.random()<0.5){
  57. this.left();
  58. }else{
  59. this.right();
  60. }
  61. if(Math.random()<0.5){
  62. this.jump();
  63. }
  64. }
  65. moveToTarget(){
  66. let targetX = 0;
  67. let targetY = 0;
  68. if(this.target instanceof Role){
  69. targetX = this.target.node.x;
  70. targetY = this.target.node.y;
  71. }else if(this.target instanceof cc.Node){
  72. targetX = this.target.x;
  73. targetY = this.target.y;
  74. }
  75. if(targetX<this.role.node.x){
  76. this.left();
  77. }else if(targetX>this.role.node.x){
  78. this.right();
  79. }
  80. if(targetY - this.role.node.y > 100){
  81. this.jump();
  82. }
  83. }
  84. leaveTarget(){
  85. let targetX = 0;
  86. let targetY = 0;
  87. if(this.target instanceof Role){
  88. targetX = this.target.node.x;
  89. targetY = this.target.node.y;
  90. }else if(this.target instanceof cc.Node){
  91. targetX = this.target.x;
  92. targetY = this.target.y;
  93. }
  94. if(targetX<this.role.node.x){
  95. this.right();
  96. }else if(targetX>this.role.node.x){
  97. this.right();
  98. }
  99. if(targetY - this.role.node.y > -100){
  100. this.jump();
  101. }
  102. }
  103. }