Button.ts 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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. this.node.on(cc.Node.EventType.TOUCH_START, this.touchStart, this);
  17. this.node.on(cc.Node.EventType.TOUCH_END, this.touchEnd, this);
  18. this.node.on("click", this.click, this);
  19. }
  20. private touchStart() {
  21. this.node_normal.active = false;
  22. this.node_pressed.active = true;
  23. this.node_disabled.active = false;
  24. }
  25. private touchEnd() {
  26. this.node_normal.active = true;
  27. this.node_pressed.active = false;
  28. this.node_disabled.active = false;
  29. }
  30. private click() {
  31. let c_count = this.onClick.length;
  32. for (let i = 0; i < c_count; i++) {
  33. if (this.onClick[i].handler) {
  34. this.onClick[i].emit([]);
  35. }
  36. }
  37. }
  38. onDestroy(){
  39. this.node.off(cc.Node.EventType.TOUCH_START, this.touchStart, this);
  40. this.node.off(cc.Node.EventType.TOUCH_END, this.touchEnd, this);
  41. this.node.off("click", this.click, this);
  42. this.onClick = [];
  43. }
  44. }