| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114 |
- import Role from "./Role";
- const {ccclass, property} = cc._decorator;
- @ccclass
- export default class Bot extends cc.Component {
- role:Role;
- target:any;
- onLoad(){
- this.role = this.node.getComponent(Role);
-
- this.schedule(this.updateOperate,0.5);
- }
- updateOperate(){
- if(this.role.saw.active){//when has saw, target a nearest other role
- let distance = 10000;
- window.controller.roles.forEach((role:Role)=>{
- if(role!=this.role&&role.isValid){
- let newDistance = this.role.node.position.sub(role.node.position).mag();
- if(newDistance<distance){
- distance = newDistance;
- this.target = role;
- }
- }
- });
- }else{//when without saw, target a nearest saw
- let distance = 10000;
- window.controller.saws.forEach((saw:cc.Node)=>{
- if(saw.isValid){
- let newDistance = this.role.node.position.sub(saw.position).mag();
- if(newDistance<distance){
- distance = newDistance;
- this.target = saw;
- }
- }
- });
- }
- if(!this.target||!this.target.isValid){//when without target, random move
- this.randomMove();
- }else{//when has target, move to target
- this.moveToTarget();
- }
- }
- left(){
- this.role.right = false;
- this.role.left = true;
- }
- right(){
- this.role.left = false;
- this.role.right = true;
- }
- jump(){
- this.role.up = true;
- this.scheduleOnce(()=>{
- this.role.up = false;
- },0.1);
- }
- randomMove(){
- if(Math.random()<0.5){
- this.left();
- }else{
- this.right();
- }
- if(Math.random()<0.5){
- this.jump();
- }
- }
- moveToTarget(){
- let targetX = 0;
- let targetY = 0;
- if(this.target instanceof Role){
- targetX = this.target.node.x;
- targetY = this.target.node.y;
- }else if(this.target instanceof cc.Node){
- targetX = this.target.x;
- targetY = this.target.y;
- }
- if(targetX<this.role.node.x){
- this.left();
- }else if(targetX>this.role.node.x){
- this.right();
- }
- if(targetY - this.role.node.y > 100){
- this.jump();
- }
- }
- leaveTarget(){
- let targetX = 0;
- let targetY = 0;
- if(this.target instanceof Role){
- targetX = this.target.node.x;
- targetY = this.target.node.y;
- }else if(this.target instanceof cc.Node){
- targetX = this.target.x;
- targetY = this.target.y;
- }
- if(targetX<this.role.node.x){
- this.right();
- }else if(targetX>this.role.node.x){
- this.right();
- }
- if(targetY - this.role.node.y > -100){
- this.jump();
- }
- }
- }
|