代码下载地址:https://gitee.com/wolfdong7/cocos_joystick
this.stick.on(cc.Node.EventType.TOUCH_MOVE, function (e) {
console.log('touch move');
// 获取触摸的位置
var w_pos = e.getLocation();
var pos = this.node.convertToNodeSpaceAR(w_pos);
var len = pos.mag();//返回该向量的长度
this.stick_dir.x = pos.x / len;
this.stick_dir.y = pos.y / len;
//不让其移出圆圈
if (len > this.max_r) {
pos.x = this.max_r * pos.x / len;
pos.y = this.max_r * pos.y / len;
}
this.stick.setPosition(pos);
}, this);
update (dt) {
if (this.joy_stick_script.stick_dir.mag() < 0.5) {
return;
}
var vx = this.joy_stick_script.stick_dir.x * this.speed; // cos(r)
var vy = this.joy_stick_script.stick_dir.y * this.speed; // sin(r)
var sx = vx * dt;
var sy = vy * dt;
this.node.x += sx;
this.node.y += sy;
/**
x=Math.atan2(1,1)
x=180*x/Math.PI//转换为角度值
trace(x)//输出:45
*/
var r = Math.atan2(this.joy_stick_script.stick_dir.y,this.joy_stick_script.stick_dir.x);
var degree = r * 180 / Math.PI;
degree = 360 - degree +90;
this.node.rotation = degree;
}
网友评论