cc.Class({
extends: cc.Component,
properties: {
},
onLoad () {
this.node.on(cc.Node.EventType.TOUCH_START, this.onTouchDown, this);
this.node.on(cc.Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
this.node.on(cc.Node.EventType.TOUCH_END, this.onTouchEnd, this);
this.node.on(cc.Node.EventType.TOUCH_CANCEL, this.onTouchEnd, this);
},
start () {
this._drag = this.node.getChildByName('Drag');
this._bg = this.node.getChildByName('Background');
this._dragR = this._drag.height / 2; //设定最大拖动半径
this._rockerV2 = cc.v2(0, 0);
this._bg.opacity = 0; //背景初始透明度
this._drag.opacity = 200; //摇杆初始透明度
},
onDestroy () {
this.node.off(cc.Node.EventType.TOUCH_START, this.onTouchDown, this);
this.node.off(cc.Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
this.node.off(cc.Node.EventType.TOUCH_END, this.onTouchEnd, this);
this.node.off(cc.Node.EventType.TOUCH_CANCEL, this.onTouchEnd, this);
},
onTouchDown(event){ //按下摇杆
if(event.getID()==0){
this.onTouchMove(event)
//点击动画
cc.tween(this._bg).to(0.6, {opacity: 150}).start();
cc.tween(this._drag).to(0.6, {opacity: 240}).start();
}
},
onTouchMove(event){ //移动摇杆
if(event.getID()==0){
let v2 = this.node.convertToNodeSpaceAR(event.getLocation());
this._rockerV2 = v2.normalize();
if(v2.mag() > this._dragR) //检测是否超出拖动半径
v2 = this._rockerV2.multiplyScalar(this._dragR);
this._drag.setPosition(v2);
}
},
onTouchEnd(event){ //抬起摇杆
if(event.getID()==0){
this._rockerV2 = cc.v2(0, 0);
this._drag.setPosition(this._rockerV2);
cc.tween(this._bg).to(0.6, {opacity: 0}).start();
cc.tween(this._drag).to(0.6, {opacity: 200}).start();
}
},
get(){ //获取摇杆坐标
let pos = this._drag.getPosition();
if(pos.mag() == 0)
return cc.v2(0, 0);
return pos.normalize() //归一化, 只要移动速度固定
//return pos.divide(this._dragR) // 摇杆不到边缘速度会递减
},
});
3个sprite 父物体绑定脚本