AutoBuild.ts 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. import { _decorator, Component, instantiate, Node, Prefab, resources, sys, UITransform } from 'cc';
  2. import { PropBase } from './Prop/Base/PropBase';
  3. import { ObjectPoolManager } from './Prop/ObjectPoolManager';
  4. import { EventManager } from './EventManager';
  5. const { ccclass, property } = _decorator;
  6. @ccclass('AutoBuild')
  7. export class AutoBuild extends Component {
  8. ISbuild = true
  9. //多少秒 生成一个
  10. Time = 0.25
  11. // 底板和地刺的生成概率
  12. Probability = [0.8, 0.2]
  13. protected onLoad(): void {
  14. ObjectPoolManager.getInstance().initializePools().then((ok) => {
  15. if (ok) {
  16. console.log('初始化成功');
  17. let floorType = [FloorType.diban, FloorType.dicin]
  18. this.schedule(() => {
  19. this.ISbuild && this.BuildOnce(floorType[this.selectByProbability()]);
  20. }, this.Time)
  21. }
  22. });
  23. }
  24. Pause(b: boolean) {
  25. this.ISbuild = b
  26. }
  27. BuildOnce(Type: FloorType) {
  28. let Node = ObjectPoolManager.getInstance().getNodeFromPool(Type, this.node)
  29. if (!Node) {
  30. console.error('没有找到节点')
  31. return
  32. }
  33. // 加一分
  34. EventManager.instance.et.emit(EventManager.EventType.Add_Score);
  35. }
  36. ClerarNode() {
  37. }
  38. getRandomNumber(min: number, max: number): number {
  39. return Math.floor(Math.random() * (max - min + 1)) + min;
  40. }
  41. public selectByProbability(): number {
  42. if (this.Probability.length === 0) {
  43. console.error('Probability array is empty');
  44. return -1;
  45. }
  46. const totalProbability = this.Probability.reduce((sum, probability) => sum + probability, 0);
  47. if (totalProbability !== 1) {
  48. console.warn('Probability array does not sum to 1, normalizing this.Probability');
  49. this.Probability = this.Probability.map(p => p / totalProbability);
  50. }
  51. const randomValue = Math.random();
  52. let cumulativeProbability = 0;
  53. for (let i = 0; i < this.Probability.length; i++) {
  54. cumulativeProbability += this.Probability[i];
  55. if (randomValue < cumulativeProbability) {
  56. return i;
  57. }
  58. }
  59. // 这个返回应该永远不会触发,因为随机值一定会小于等于 1
  60. return this.Probability.length - 1;
  61. }
  62. }
  63. export enum FloorType {
  64. diban = 'diban',//预制体的名称
  65. dicin = 'dici',
  66. }