// Learn TypeScript:
// - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/typescript.html
// - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/typescript.html
// Learn Attribute:
// - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
// - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
// - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
// - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/life-cycle-callbacks.html
const { ccclass, property } = cc._decorator;
@ccclass
export default class NewClass extends cc.Component {
// this.node 是需要移動的節點
nodePos = null;
onLoad() {
//節點初始位置,每次觸摸結束更新
this.nodePos = this.node.getPosition();
//觸摸監聽(this.node.parent是屏幕)
//想達到按住節點,節點才能移動的效果,將監聽函數註冊到 this.node 上,去掉 .parent 即可
this.node.parent.on(cc.Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
this.node.parent.on(cc.Node.EventType.TOUCH_END, this.onTouchEnd, this);
this.node.parent.on(cc.Node.EventType.TOUCH_CANCEL, this.onTouchCancel, this);
}
//觸摸移動;
onTouchMove(event) {
var self = this;
var touches = event.getTouches();
//觸摸剛開始的位置
var oldPos = self.node.parent.convertToNodeSpaceAR(touches[0].getStartLocation());
//觸摸時不斷變更的位置
var newPos = self.node.parent.convertToNodeSpaceAR(touches[0].getLocation());
//var subPos = cc.pSub(oldPos,newPos); 1.X版本是cc.pSub
var subPos = oldPos.sub(newPos); // 2.X版本是 p1.sub(p2);
self.node.x = self.nodePos.x - subPos.x;
self.node.y = self.nodePos.y - subPos.y;
// 控制節點移不出屏幕;
var minX = -self.node.parent.width / 2 + self.node.width / 2; //最小X座標;
var maxX = Math.abs(minX);
var minY = -self.node.parent.height / 2 + self.node.height / 2; //最小Y座標;
var maxY = Math.abs(minY);
var nPos = self.node.getPosition(); //節點實時座標;
if (nPos.x < minX) {
nPos.x = minX;
};
if (nPos.x > maxX) {
nPos.x = maxX;
};
if (nPos.y < minY) {
nPos.y = minY;
};
if (nPos.y > maxY) {
nPos.y = maxY;
};
self.node.setPosition(nPos);
}
onTouchEnd() {
this.nodePos = this.node.getPosition(); //獲取觸摸結束之後的node座標;
}
onTouchCancel() {
this.nodePos = this.node.getPosition(); //獲取觸摸結束之後的node座標;
}
}