SettingData.ts 3.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. import { _decorator, sys } from 'cc';
  2. import { Constants } from './Constants';
  3. import { Utils } from '../utils/Utils';
  4. import { Singleton } from '../core/manager/Singleton';
  5. import { audioMgr } from '../core/manager/AudioManager';
  6. import MsgHints from '../utils/MsgHints';
  7. const { ccclass, property } = _decorator;
  8. @ccclass("SettingData")
  9. class SettingData extends Singleton{
  10. private _data: any = null;
  11. public get data() {
  12. if (!this._data) {
  13. this.loadFromCache();
  14. //使用Proxy代理data对象 拦截属性修改
  15. this._data = new Proxy(this._data, {
  16. set: (target, prop, value) => {
  17. target[prop] = value;
  18. this.saveToCache();
  19. if (prop === "bgMusic") {//如果是bgMusic 变化 自动处理音乐逻辑
  20. MsgHints.show(value? `bg music has been turned on`:`bg music has been turned off`);
  21. if(value) {
  22. audioMgr.play(Constants.audios.BGM, true);
  23. } else {
  24. audioMgr.stop(Constants.audios.BGM);
  25. }
  26. }else if(prop === "soundFx") {//如果是bgMusic 变化
  27. MsgHints.show(value?`sound has been turned on`:`sound has been turned off`);
  28. }else if(prop === "vibrate") {//如果是vibration 变化
  29. MsgHints.show(value?`vibrate has been turned on`:`vibrate has been turned off`);
  30. }
  31. return true;
  32. }
  33. });
  34. }
  35. return this._data;
  36. }
  37. /**
  38. * 读取数据缓存
  39. */
  40. public loadFromCache(){
  41. let l = sys.localStorage.getItem(Constants.localCache.settingData);
  42. if(l){
  43. this._data = JSON.parse(Utils.decrypt(l));
  44. }else{
  45. //没有数据保存一份默认的初始数据
  46. this._data = {
  47. bgMusic: true,//背景音乐开关
  48. soundFx: true,//音效开关
  49. vibrate: false,//震动开关
  50. sensitivity: 0.2 //相机旋转的灵敏度 值越大移动越快 灵敏度越高
  51. }
  52. this.saveToCache();
  53. }
  54. return this.data;
  55. }
  56. /**
  57. * 得到设置的数据数组
  58. */
  59. public getSettingDatas() {
  60. const displayNames = ["背景音乐", "音效", "震动"];
  61. const dataKeys = Object.keys(this.data);
  62. //确保字段顺序一致
  63. return dataKeys.map((key, index) => ({
  64. name: displayNames[index],
  65. selected: this.data[key]
  66. }));
  67. }
  68. /**
  69. * 保存到缓存中
  70. */
  71. public saveToCache(){
  72. const data = JSON.stringify(this.data);
  73. //序列化JSON字符串过后加密存储
  74. sys.localStorage.setItem(Constants.localCache.settingData, Utils.encrypt(data));
  75. }
  76. /**
  77. * 删除缓存
  78. */
  79. public remove(){
  80. sys.localStorage.removeItem(Constants.localCache.settingData);
  81. this.loadFromCache();
  82. }
  83. }
  84. //全局单例
  85. export const settingData = SettingData.ins();