COCOS导航组件

@COCOS 导航组件
关于想在COCOS里面实现导航功能,可用于敌人追踪主角或者是坐标点自动导航;
话不多说,直接上脚本代码,脚本文件名为lock

cc.Class({
    extends: cc.Component,

    properties: {
        speed:{type:cc.Integer,default:200,tooltip:"运动速度"},
    },

    //导航函数
    walkToDst(dst){
        //位移,距离,速度,时间,向量
        var src = this.node.getPosition();
        console.log("lock里的SRC"+src);
        var dir = dst.sub(src);
        var len = dir.mag();

        if(len<=0){
            return;
        }
        //计算起终点时间
        this.walkTime = len/this.speed;

        this.vx= this.speed * dir.x /len;
        this.vy = this.speed * dir.y/len;

        this.isWalking = true;
        this.passedTime = 0;//计时器
    },

    start () {
        this.isWalking = false;
        this.walkTime = 0;
        this.vy = 0 ;
        this.vx = 0 ;
        this.passedTime = 0;
    }, 

     update (dt) {
         if(this.isWalking ===false){
             return;
         }
         this.passedTime +=dt;
         if(this.passedTime >= this.walkTime){
             dt -=(this.passedTime - this.walkTime);//纠正刷新间隔
         }

         this.node.x += this.vx * dt;
         this.node.y += this.vy * dt;

         if(this.passedTime >= this.walkTime){
           this.isWalking = false;
        }
     },
});

其中walkToDst(dst)要求传入一个坐标参数dst,speed用于更改其速度。
这个脚本相当于提供了一个函数walkToDst(dst)让它可以自动的去追踪目标(哪怕是动态目标)

以下是一种引用示例,新建一个脚本,属性为target,即你要追踪的目标,然后通过拿到导航组件名(“lock”)去拿到这个方法,然后使用这个函数就可以导航了。
当然应该有更好的引用方式,但是我是初次接触COCOS,所以目前想到的是在update函数中动态追踪。

cc.Class({
    extends: cc.Component,

    properties: {
        target:{type:cc.Node,default:null,tooltip:"导航目标"},
    },

    // LIFE-CYCLE CALLBACKS:
   
    onLoad () {

    },

    start () {

    },

    update (dt) {
        var src = this.target.getPosition();
        var agent = this.node.getComponent("lock");
        agent.walkToDst(src);
    },
});

注明:使用的时候一定要把两个脚本都挂在一个节点上。否则getComponent方法会拿不到lock脚本(即导航脚本)

发布了1 篇原创文章 · 获赞 0 · 访问量 1

猜你喜欢

转载自blog.csdn.net/weixin_43890220/article/details/105532433
今日推荐