Cocos Creator 拖動效果

我們要實現的效果是,按住並拖動一個小物體,物體跟隨手指(鼠標)移動。

代碼DragToAnywhere.ts

const { ccclass, property } = cc._decorator;

@ccclass
export default class DragToAnywhere extends cc.Component {

    @property(cc.Label)
    label: cc.Label = null;

    start () {
        
    }

    onEnable() {
        this.node.on(cc.Node.EventType.TOUCH_MOVE, this._onTouchMove, this);
        this.node.on(cc.Node.EventType.TOUCH_END, this._onTouchEnd, this);
    }

    onDisable() {
        this.node.off(cc.Node.EventType.TOUCH_MOVE, this._onTouchMove, this);
        this.node.off(cc.Node.EventType.TOUCH_END, this._onTouchEnd, this);
    }

    // update (dt) {}

    _onTouchMove(touchEvent) {
        let location = touchEvent.getLocation();
        this.node.position = this.node.parent.convertToNodeSpaceAR(location); // 確定位置
    }

    _onTouchEnd(touchEvent) {
        // 放下
    }
}

DragToAnywhere.ts掛在預製體上。在場景中創建預製體對象。

let node1 = cc.instantiate(this.drag_item);
this.node.addChild(node1);
node1.x = 100;
node1.y = 100;
node1.getComponent(DragToAnywhere).label.string = '水星';

運行效果

工程請查看github/CCCTry

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章