Cocos Creatorタッチスクリーンの任意の位置ノードが指に従って移動します。

2635 ワード

// 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  ;
    }
}