cocos creator 摇杆设计

最近无事整理了下摇杆的制作,参考了网上的一篇博客 博客地址

思路如下:

1.以角度计算摇杆摇动方向
2.以点击位置判断摇杆摇动方向
3.通过连续move方法落点位置的位移差以及移动角度计算

参考后采用了角度计算的方法。其中难点在于关于圆的一些数学知识(早就还给老师了)

  • 圆的标准方程:(x-a)^2+(y-b)^2=r^2
  • 弧长公式: l = n*pi*r/180
  • dX = x2 - x1 dY = y2 - y1 Math.atan(dY/dX)

源码提交在github

//摇杆跟随逻辑
let pos = this.panelNode.convertToNodeSpaceAR(event.getLocation()); 
let radius = Math.sqrt(Math.pow(pos.x,2) + Math.pow(pos.y,2));
if(radius <= this.backgroundNode.width/2) {
    this.frontNode.setPosition(pos);
} else {
    let posX = Math.cos(Math.atan2(pos.y,pos.x)) * (this.backgroundNode.width/2); 
    let posY = Math.sin(Math.atan2(pos.y,pos.x)) * (this.backgroundNode.width/2); 
    this.frontNode.setPosition(posX,posY);
}
//方向计算逻辑
this.angle = Math.atan2(pos.y,pos.x) * (180 / Math.PI);


fourOrientationExcute : function ()
{
    if (this.angle > 45 && this.angle < 135) {                                              //上
        this.bodyObj.y += this.speed;
    } else if (this.angle > -135 && this.angle < -45) {                                     //下
        this.bodyObj.y -= this.speed;
    } else if (this.angle < -135 && this.angle > -180 || this.angle > 135 && this.angle < 180) {      //左
        this.bodyObj.x -= this.speed;
    } else if (this.angle < 0 && this.angle > -45 || this.angle > 0 && this.angle < 45) {             //右
        this.bodyObj.x += this.speed;
    }  
},

allOrientationExcute: function () {  
    if(this.angle === 0) { return; }
    this.bodyObj.x += Math.cos(this.angle * (Math.PI / 180)) * this.speed;  
    this.bodyObj.y += Math.sin(this.angle * (Math.PI / 180)) * this.speed;  
}, 

eightOrientationExcute: function () { 
   if (this.angle > 67.5 && this.angle < 112.5) {  
       this.bodyObj.y += this.speed;  
   } else if (this.angle > -112.5 && this.angle < -67.5) {  
       this.bodyObj.y -= this.speed;  
   } else if (this.angle < -157.5 && this.angle > -180 || this.angle > 157.5 && this.angle < 180) {  
       this.bodyObj.x -= this.speed;  
   } else if (this.angle < 0 && this.angle > -22.5 || this.angle > 0 && this.angle < 22.5) {  
       this.bodyObj.x += this.speed;  
   } else if (this.angle > 112.5 && this.angle < 157.5) {  
       this.bodyObj.x -= this.speed / 1.414;  
       this.bodyObj.y += this.speed / 1.414;  
   } else if (this.angle > 22.5 && this.angle < 67.5) {  
       this.bodyObj.x += this.speed / 1.414;  
       this.bodyObj.y += this.speed / 1.414;  
   } else if (this.angle > -157.5 && this.angle < -112.5) {  
       this.bodyObj.x -= this.speed / 1.414;  
       this.bodyObj.y -= this.speed / 1.414;  
   } else if (this.angle > -67.5 && this.angle < -22.5) {  
       this.bodyObj.x += this.speed / 1.414;  
       this.bodyObj.y -= this.speed / 1.414;  
   }  
},
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值