cc.Class({
extends: cc.Component,
properties: {
Max_r:100,
},
// use this for initialization
onLoad: function () {
this.speed = 300 //移动速度
this.xiao = cc.find('Rocker/xiao') //中间小摇杆
this.Rocker = cc.find('Rocker') //摇杆整体
this.sprite = cc.find('sprite') //角色Role
this.dir = cc.v2(0,0);
this.xiao.on(cc.Node.EventType.TOUCH_START,function(e){
var w_pos = e.getLocation();
var pos = this.Rocker.convertToNodeSpaceAR(w_pos);//将世界坐标转化为父节点的相对坐标
var len = pos.mag();
this.dir.x = pos.x / len;
this.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.xiao.setPosition(pos);
},this);
this.xiao.on(cc.Node.EventType.TOUCH_MOVE,function(e){
var w_pos = e.getLocation();
var pos = this.Rocker.convertToNodeSpaceAR(w_pos);//将世界坐标转化为父节点的相对坐标
var len = pos.mag();
this.dir.x = pos.x / len;
this.dir.y = pos.y / len;
console.log(this.dir.x);
console.log(this.dir.y);
if(len > this.Max_r){
pos.x = this.Max_r * pos.x / len;
pos.y = this.Max_r * pos.y / len;
}
this.xiao.setPosition(pos);
},this);
this.xiao.on(cc.Node.EventType.TOUCH_END,function(e){
this.xiao.setPosition(cc.v2(0,0));
this.dir = cc.v2(0, 0);
},this);
this.xiao.on(cc.Node.EventType.TOUCH_CANCEL,function(e){
this.xiao.setPosition(cc.v2(0,0));
this.dir = cc.v2(0, 0);
},this);
},
// called every frame
update: function (dt) {
if(this.dir.mag() < 0.5){
return;
}
var vx = this.dir.x * this.speed;
var vy = this.dir.y * this.speed;
var sx = vx * dt;
var sy = vy * dt;
//移动
this.sprite.x += sx;
this.sprite.y += sy;
//方向计算
var r = Math.atan2(this.dir.y,this.dir.x);
var degree = r * 180/(Math.PI);
degree = - degree + 90;
this.sprite.rotation = degree;
},
});