ProcessBar.ts 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. import { _decorator, CCFloat, Component, Node, Sprite, UITransform } from 'cc';
  2. const { ccclass, property } = _decorator;
  3. @ccclass('ProcessBar')
  4. export class ProcessBar extends Component {
  5. // 进度条
  6. @property(Sprite)
  7. processBar = null;
  8. // 跟随进度条的Node
  9. @property(Node)
  10. followNode = null
  11. // 记录开始坐标
  12. startPostiton_x = null;
  13. // 记录进度条总长
  14. barSize = null
  15. padding =0
  16. init(prcent?,padding=0) {
  17. // // 进度条
  18. this.padding = padding
  19. this.initProcessBar(prcent);
  20. }
  21. initProcessBar(ratio?: number) {
  22. ratio = ratio || 0;
  23. let sprite = this.processBar;
  24. sprite.fillRange = ratio;
  25. // 根据比率初始化x坐标一般(0,0)是中心点
  26. let position = this.processBar.node.parent.position
  27. // 获取进度条宽度
  28. let uit: UITransform = this.processBar.getComponent(UITransform)
  29. let contentSize = uit.contentSize;
  30. // y坐标调好了,不需要动态生成,只需要计算x的偏移量,默认x - contentSize/2
  31. let offSet_x = position.x - (contentSize.width * uit.anchorX)+this.padding;
  32. this.startPostiton_x = offSet_x;
  33. this.barSize = contentSize.width - 2*this.padding;
  34. }
  35. getFollowPostion_x() {
  36. return this.startPostiton_x + this.barSize * this.processBar.fillRange;
  37. }
  38. // @property(CCFloat)
  39. // set ratio (ratio:number){
  40. // this._ratio = ratio
  41. // this.init(0, 35)
  42. // this.set(ratio)
  43. // }
  44. // // @property(CCFloat)
  45. // get ratio (){
  46. // return this._ratio
  47. // }
  48. // @property(CCFloat)
  49. // _ratio:number
  50. set(ratio: number) {
  51. ratio = Math.min(ratio, 1)
  52. ratio = Math.max(ratio, 0)
  53. this.processBar.fillRange = ratio;
  54. // // 实际x坐标
  55. if (this.followNode) {
  56. // let real_x = this.startPostiton_x + this.barSize * ratio;
  57. this.followNode?.setPosition(this.getFollowPostion_x(), this.followNode.position.y)
  58. }
  59. }
  60. getFollowNodeW_Pos(){
  61. return this.followNode?.worldPosition
  62. }
  63. // getFollowPosByRatio(ratio){
  64. // }
  65. }