欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

CocosCreator控制物体移动

程序员文章站 2024-03-16 23:05:28
...

写了一个简单的实现·上下左右四个方向移动的脚本
代码如下,挂栽直接可以运行

properties: {
        //玩家移动速度
        MoveSpeed:0,
    },

    // LIFE-CYCLE CALLBACKS:

    onLoad () {
        //定义移动开关
        this.left=false;
        this.right=false;
        this.up=false,
        this.down=false;
        
        //初始化键盘输入监听
        cc.systemEvent.on(cc.SystemEvent.EventType.KEY_DOWN,this.onKeyDown,this);
        cc.systemEvent.on(cc.SystemEvent.EventType.KEY_UP,this.onKeyUp,this);
    },

    start () {
   
    },

    update (dt) {
         //根据要移动的方向更新主角速度
         //左右移动
         if(this.left){
             this.node.x-=this.MoveSpeed*dt;
         }else if(this.right){
            this.node.x+=this.MoveSpeed*dt;
         }
         //上下移动
         if(this.down){
            this.node.y-=this.MoveSpeed*dt;
        }else if(this.up){
           this.node.y+=this.MoveSpeed*dt;
        }
    },

    onKeyDown(event){
        //设置对应按键按下发生的事件
        switch(event.keyCode){
            //按下A键
            case cc.macro.KEY.a:
              this.left=true;
            break;
            case cc.macro.KEY.d:
              this.right=true;
            break;
            case cc.macro.KEY.w:
              this.up=true;
            break;
            case cc.macro.KEY.s:
              this.down=true;
            break;
        }
    },

    onKeyUp(event){
        //设置按键抬起后的事件
        switch(event.keyCode){
            //按下A键
            case cc.macro.KEY.a:
              this.left=false;
            break;
            case cc.macro.KEY.d:
              this.right=false;
            break;
            case cc.macro.KEY.w:
              this.up=false;
            break;
            case cc.macro.KEY.s:
              this.down=false;
            break;
        }
    },

如果要实现八方向的原理差不多
无非就是在向另外四个方向移动的时候
同时改变x.y轴的坐标