Cocos Creator 拖动去指定区域

Cocos Creator 拖动去指定区域,第1张

概述我们要实现的效果是,按住并拖动一个小物体,物体跟随手指(鼠标)移动。 拖到指定位置放下。如果没有到指定位置,则回到上一个位置。 新建脚本DragToTarget.ts,挂到预制体上。 const {

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

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

const { ccclass,property } = cc._decorator;@ccclassexport 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);        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) {        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的时候,判断自己是否在目标区域内。
如果不在则返回上一个坐标。

在场景中使用

import DragToTarget from "./DragToTarget";const { ccclass,property } = cc._decorator;@ccclassexport 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++;    }}

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

总结

以上是内存溢出为你收集整理的Cocos Creator 拖动去指定区域全部内容,希望文章能够帮你解决Cocos Creator 拖动去指定区域所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/998926.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-21
下一篇 2022-05-21

发表评论

登录后才能评论

评论列表(0条)

保存