前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Cocos Creator 拖动去指定区域

Cocos Creator 拖动去指定区域

作者头像
AnRFDev
发布2021-02-01 15:19:16
1.7K0
发布2021-02-01 15:19:16
举报
文章被收录于专栏:AnRFDevAnRFDev

我们要实现的效果是,按住并拖动一个小物体,物体跟随手指(鼠标)移动。 拖到指定位置放下。如果没有到指定位置,则回到上一个位置。

新建脚本DragToTarget.ts,挂到预制体上。

代码语言:javascript
复制
const { ccclass, property } = cc._decorator;
@ccclass
export default class DragToTarget extends cc.Component {

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

    @property(cc.Node)
    targetOfDragList: cc.Node[] = [];

    _oldPos = null; // 上一个位置

    start() {
        this._oldPos = this.node.position;
    }

    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) {
        if (this.targetOfDragList.length === 0) {
            return; // 没有目标位置
        }
        let inTarget = false;
        for (const targetNode of this.targetOfDragList) {
            if (this._withinTarget(targetNode, touchEvent)) {
                inTarget = true;
                break;
            }
        }
        if (!inTarget) {
            this.node.position = this._oldPos; // 回去
        }
    }

    // 判断触摸事件是否在槽位里
    _withinTarget(targetNode: cc.Node, touchEvent) {
        let rect = targetNode.getBoundingBox();
        let location = touchEvent.getLocation();
        let point = targetNode.parent.convertToNodeSpaceAR(location);
        return rect.contains(point);
    }
}

思路与之前的拖动类似。

在最后TOUCH_END的时候,判断自己是否在目标区域内。

如果不在则返回上一个坐标。

在场景中使用

代码语言:javascript
复制
import DragToTarget from "./DragToTarget";

const { ccclass, property } = cc._decorator;

@ccclass
export default class DragToControl extends cc.Component {

    @property(cc.Prefab)
    drag_to_item: cc.Prefab = null;

    @property(cc.Node)
    dragTargets: cc.Node[] = [];

    itemNum = 1;

    start() {
        this.createItem();
    }

    // update (dt) {}

    createItem() {
        let d = cc.instantiate(this.drag_to_item);
        this.node.addChild(d);
        let dragTo = d.getComponent(DragToTarget);
        dragTo.targetOfDragList = this.dragTargets; // 设置目的地
        dragTo.nameLabel.string = '' + this.itemNum++;
    }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-12-30,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档