AutoBuild.ts 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. EventManager.instance.et.emit(EventManager.EventType.initOver);
  18. let floorType = [FloorType.diban, FloorType.dicin]
  19. this.ISbuild && this.BuildOnce(FloorType.diban);
  20. this.schedule(() => {
  21. this.ISbuild && this.BuildOnce(floorType[this.selectByProbability()]);
  22. }, this.Time)
  23. }
  24. });
  25. }
  26. Pause(b: boolean) {
  27. this.ISbuild = b
  28. }
  29. BuildOnce(Type: FloorType) {
  30. let Node = ObjectPoolManager.getInstance().getNodeFromPool(Type, this.node)
  31. if (!Node) {
  32. console.error('没有找到节点')
  33. return
  34. }
  35. return Node
  36. }
  37. ClerarNode() {
  38. }
  39. getRandomNumber(min: number, max: number): number {
  40. return Math.floor(Math.random() * (max - min + 1)) + min;
  41. }
  42. public selectByProbability(): number {
  43. if (this.Probability.length === 0) {
  44. console.error('Probability array is empty');
  45. return -1;
  46. }
  47. const totalProbability = this.Probability.reduce((sum, probability) => sum + probability, 0);
  48. if (totalProbability !== 1) {
  49. console.warn('Probability array does not sum to 1, normalizing this.Probability');
  50. this.Probability = this.Probability.map(p => p / totalProbability);
  51. }
  52. const randomValue = Math.random();
  53. let cumulativeProbability = 0;
  54. for (let i = 0; i < this.Probability.length; i++) {
  55. cumulativeProbability += this.Probability[i];
  56. if (randomValue < cumulativeProbability) {
  57. return i;
  58. }
  59. }
  60. // 这个返回应该永远不会触发,因为随机值一定会小于等于 1
  61. return this.Probability.length - 1;
  62. }
  63. }
  64. export enum FloorType {
  65. diban = 'diban',//预制体的名称
  66. dicin = 'dici',
  67. }