DragSource.ts 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import { Component, EventHandler, EventTouch, v3, Vec3, _decorator } from "cc";
  2. import { DragSystem } from "./DragSystem";
  3. import { DragTarget } from "./DragTarget";
  4. const { ccclass, property } = _decorator;
  5. /**
  6. * 可以被拖拽的组件
  7. * @description 如果需要新创建UI,那么请自己创建预制体,并在预制体的update中更新其坐标为本组件的worldPosition
  8. * @author 袁浩
  9. */
  10. @ccclass("DragSource")
  11. export class DragSource extends Component {
  12. @property({ tooltip: "所属分组" })
  13. public group: string = "group";
  14. @property({ tooltip: "是否更新自己的坐标" })
  15. public updatePosition = false;
  16. @property({ tooltip: "当被拖拽", type: EventHandler })
  17. public onDrag: EventHandler[] = [];
  18. @property({ tooltip: "当被拖拽放下", type: EventHandler })
  19. public onDrop: EventHandler[] = [];
  20. @property({ tooltip: "当被拖拽中", type: EventHandler })
  21. public onDraging: EventHandler[] = [];
  22. /**
  23. * 当前世界位置
  24. */
  25. public worldPosition: Vec3;
  26. start() {
  27. DragSystem.addSource(this);
  28. }
  29. onDestroy() {
  30. DragSystem.removeSource(this);
  31. }
  32. update() {
  33. if (this.updatePosition && this.worldPosition) {
  34. this.node.worldPosition = this.worldPosition;
  35. }
  36. }
  37. public draging(event: EventTouch) {
  38. for (let i = 0; i < this.onDraging.length; i++) {
  39. this.onDraging[i] && this.onDraging[i].emit([event]);
  40. }
  41. }
  42. public drop(event: EventTouch) {
  43. for (let i = 0; i < this.onDrop.length; i++) {
  44. this.onDrop[i] && this.onDrop[i].emit([event]);
  45. }
  46. }
  47. public drag(event: EventTouch) {
  48. for (let i = 0; i < this.onDrag.length; i++) {
  49. this.onDrag[i] && this.onDrag[i].emit([event]);
  50. }
  51. }
  52. }