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