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);
        this.node.off(cc.Node.EventType.TOUCH_END,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

参考:
Cocos Creator: https://rustfisher.com/categories/CocosCreator/

相关文章

    本文实践自 RayWenderlich、Ali Hafizji 的文章《...
Cocos-code-ide使用入门学习地点:杭州滨江邮箱:appdevzw@1...
第一次開始用手游引擎挺激动!!!进入正题。下载资源1:从C...
    Cocos2d-x是一款强大的基于OpenGLES的跨平台游戏开发...
1.  来源 QuickV3sample项目中的2048样例游戏,以及最近《...
   Cocos2d-x3.x已经支持使用CMake来进行构建了,这里尝试...