cocosCreator中常见的几种主角控制方式

1. 蛇蛇大作战主角控制方式,主角根据 鼠标按下经过的轨迹移动

要用到触摸事件中的touchMove事件。具体实现如下:

 touchStartEvent(event)
   {
      let touches=event.getTouches();
      let touchPos=touches[0].getLocation();
      this.isMoving=true;
      this.nextPos=this.node.convertToNodeSpaceAR(touchPos); 
   }
   
   touchMoveEvent(event)
   {
       let touches=event.getTouches();
       let touchPos=touches[0].getLocation();
       this.nextPos=this.node.convertToNodeSpaceAR(touchPos); 

   }

   touchEndEvent(event)
   {
       this.isMoving=false;      
   }

   update(dt)
   {
       if(!this.isMoving)  
       return;
       let oldPos=this.player.position;
       let dir=this.nextPos.sub(oldPos).normalize();
       let newPos =oldPos.add(dir.mul(this.moveSpeed*dt));  
       this.player.setPosition(newPos);
   }

在实际运行过程中,当player移动到鼠标所在位置时,鼠标如果仍在原地,player 会出现颤抖,原因是update方法每帧执行,每帧都在setposition,没有结束moving状态导致。

2.人物朝鼠标点击位置移动

LoL中人物移动方式

实现如下: 使用touchStart 方式

  touchStartEvent(event)
   {
    //   let touches=event.getTouches();
    //   let touchPos=touches[0].getLocation();
      let touchPos=event.getLocation();
      let worldPos;
      //视口坐标--->世界坐标(如果摄像机在0,0 位置,则不需要转换。否则需要转换坐标系)
      worldPos= this.cameraMain.getCameraToWorldPoint(touchPos, worldPos);
      //世界坐标--->节点坐标
      let targetPos=this.node.convertToNodeSpaceAR(worldPos);
      this.walkToTarget(targetPos);
     
   }
   
   walkToTarget(dst:cc.Vec2)
   {
       let nowPos=this.player.position;
       let dir=dst.sub(nowPos);
       let len=dir.mag();
       if(len<=0)
       {
           return;
       }
       this.walkTime=len/this.moveSpeed;
       this.timeVal=0;
       this.vx=this.moveSpeed*(dir.x/len);
       this.vy=this.moveSpeed*(dir.y/len);
       this.isMoving=true;
   }

   update(dt)
   {
        if(!this.isMoving)  return;
         
        this.timeVal+=dt;
        if(this.timeVal>this.walkTime)
        {
            dt-=(this.timeVal-this.walkTime);
        }

        let sx=this.vx*dt;
        let sy=this.vy*dt;
        this.player.x+=sx;
        this.player.y+=sy;

        if(this.timeVal>=this.walkTime)
        {
            this.isMoving=false;
        }
   }

注意视口坐标和世界坐标以及结点坐标的转换,当相机的位置 和远点位置相同的时候,则不需要转换视口坐标到世界坐标,如果不与原点重合,则需要转换坐标,才能正确转入到节点坐标。

3.飞机大战 的移动方式

手指点击到飞机上,飞机跟着手指的运动运动

实现如下:

 touchMoveEvent(event)
    {
        let worldPos;
        worldPos=this.cameraMain.getCameraToWorldPoint(event.getLocation(),worldPos);
        let nodePos=this.node.convertToNodeSpaceAR(worldPos);
        this.player.setPosition(nodePos);
    }

 

  • 2
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值