Button.ts 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. const { ccclass, property } = cc._decorator;
  2. @ccclass
  3. export default class Button extends cc.Component {
  4. @property({ type: cc.Node, displayName: "正常" })
  5. node_normal: cc.Node = null;
  6. @property({ type: cc.Node, displayName: "按下" })
  7. node_pressed: cc.Node = null;
  8. @property({ type: cc.Node, displayName: "禁用" })
  9. node_disabled: cc.Node = null;
  10. @property({ displayName: "点击函数", type: cc.Component.EventHandler })
  11. public onClick: cc.Component.EventHandler[] = [];
  12. onLoad() {
  13. this.touchEnd();
  14. }
  15. start() {
  16. if (!this.node.getComponent(cc.Button)) {
  17. this.node.addComponent(cc.Button);
  18. }
  19. this.node.on(cc.Node.EventType.TOUCH_START, this.touchStart, this);
  20. this.node.on(cc.Node.EventType.TOUCH_END, this.touchEnd, this);
  21. this.node.on("click", this.click, this);
  22. }
  23. private touchStart() {
  24. this.node_normal.active = false;
  25. this.node_pressed.active = true;
  26. this.node_disabled.active = false;
  27. }
  28. private touchEnd() {
  29. this.node_normal.active = true;
  30. this.node_pressed.active = false;
  31. this.node_disabled.active = false;
  32. }
  33. private click() {
  34. let c_count = this.onClick.length;
  35. for (let i = 0; i < c_count; i++) {
  36. if (this.onClick[i].handler) {
  37. this.onClick[i].emit([]);
  38. }
  39. }
  40. }
  41. onDestroy() {
  42. this.node.off(cc.Node.EventType.TOUCH_START, this.touchStart, this);
  43. this.node.off(cc.Node.EventType.TOUCH_END, this.touchEnd, this);
  44. this.node.off("click", this.click, this);
  45. this.onClick = [];
  46. }
  47. }