最近无事整理了下摇杆的制作,参考了网上的一篇博客 博客地址
思路如下:
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;
}
},