Cocos Creator個性化時間進度條實現


前言

在Cocos Creator游戲開發中,經常需要使用個性化時間進度條,下面,我們就一起來封裝下自己的個性化時間進度條組件。

一、個性化時間進度條

1: 編寫腳本, 來使用sprite的扇形來顯示當前的進度: 屬性: time_sec: 定時器的時間 clockwise: 是否為順時針或逆時針; reverse: 是否反轉 startClockAction: 開始累積時間,看時間過去的百分比,來改變精靈顯示的百分比; stopClockAction: 停止計時累積;

二、計時器控制組件


1. `@ccclass` 2. `export default class ClockCtrl extends cc.Component {` 3. ` @property({tooltip:"計時時長"})` 4. ` actionTime : number = 10;` 5. ` @property({tooltip:"是否逆時針"})` 6. ` clockWise : boolean = false;` 7. ` @property({tooltip:"計時方向"})` 8. ` reverse : boolean = false; // false,由少變多` 9. ` @property({tooltip:"是否在加載的時候就開始計時"})` 10. `playOnLoad : boolean = false;` 11. ` private nowTime : number = 0; // 用於記錄已經過去的時間` 12. ` private isRuning : boolean = false; // 計時器是否正在行走` 13. ` private sprite : cc.Sprite;` 14. `private endFunc : Function = null;` 15. ` onLoad () {` 16. ` this.node.active = false;` 17. ` // 獲取子節點上的Sprite組件` 18. ` this.sprite = this.node.getChildByName("TimerBar").getComponent(cc.Sprite);` 19. ` if(this.playOnLoad){` 20. ` this.startClockAction(this.actionTime, this.endFunc);` 21. ` }` 22. `}` 23. ` startClockAction(actionTime : number, endFunc : Function){` 24. ` if(actionTime <= 0){` 25. ` return;` 26. ` }` 27. ` this.endFunc = endFunc;` 28. ` this.node.active = true;` 29. ` this.actionTime = actionTime;` 30. ` this.nowTime = 0;` 31. ` this.isRuning = true;` 32. `}` 33. ` stopClockAction(){` 34. ` this.node.active = false;` 35. ` this.isRuning = false;` 36. `}` 37. ` update (dt : number) {` 38. ` if(!this.isRuning){` 39. ` return;` 40. ` }` 41. ` this.nowTime += dt;` 42. ` // 將時間轉換為百分比,設置給this.sprite的FillRange屬性` 43. ` let per : number = this.nowTime/this.actionTime;` 44. ` if(per > 1){` 45. ` per = 1;` 46. ` this.isRuning = false;` 47. ` if(this.endFunc){` 48. ` this.endFunc();` 49. ` }` 50. ` }` 51. ` // 進度條 由多變少的控制` 52. ` // per : 0 0.5 1 ` 53. ` // 1-per:1 0.5 0` 54. ` if(this.reverse){` 55. ` per = 1 - per;` 56. ` }` 57. ` // 順時針和逆時針的控制` 58. ` if(this.clockWise){` 59. ` per = -per;` 60. ` }` 61. ` this.sprite.fillRange = per;` 62. ` }` 63. `}` </pre> 

三、UI組件

四、組件的使用測試GameMgr.ts


1. `const {ccclass, property} = cc._decorator;` 2. `@ccclass` 3. `export default class GameMgrextends cc.Component { ` 4. ` @property({type:ClockCtrl, tooltip:"計時器組件"})` 5. ` clock : ClockCtrl = null;` 6. ` @property({tooltip:"計時器計時時長"})` 7. ` actionTime : number = 5;` 8. ` private endFunc(){` 9. ` console.log(this.actionTime,"秒倒計時完成!");` 10. ` }` 11. ` start(){` 12. ` this.clock.startClockAction(this.actionTime, this.endFunc);` 13. `}` 14. `}` </pre> 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM