-
Notifications
You must be signed in to change notification settings - Fork 0
/
LevelAssembler.cs
93 lines (72 loc) · 2.88 KB
/
LevelAssembler.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
using System.Collections.Generic;
using UnityEngine;
public class LevelAssembler : Singleton<LevelAssembler>
{
private List<LevelID> possibleLevels = new List<LevelID>();
[SerializeField]
private float probabilityToAdd;
private List<float> GetProbabilityList(List<LevelID> _possibleLevels)
{
List<float> probabilities = new List<float>();
ScriptableLevelChunk levelChunk;
for (int i = 0; i < _possibleLevels.Count; i++)
{
levelChunk = ResourceSystem.Instance.GetLevelChunk(_possibleLevels[i]);
float probability = levelChunk.Probability;
probabilities.Add(probability);
}
return probabilities;
}
private int GetWeightedRandomIndex(List<float> probabilities)
{
float totalProbability = 0;
for (int i = 0; i < probabilities.Count; i++)
{
totalProbability += probabilities[i];
}
float randomValue = Random.Range(0, totalProbability);
for (int i = 0; i < probabilities.Count; i++)
{
randomValue -= probabilities[i];
if (randomValue <= 0)
{
return i;
}
}
return probabilities.Count - 1;
}
public void CreateLevelChunk(LevelID _nextLevelID, Transform parentObject)
{
ScriptableLevelChunk scriptableLevelChunk = ResourceSystem.Instance.GetLevelChunk(_nextLevelID);
GameObject GO = Instantiate(scriptableLevelChunk.LevelPrefab, parentObject);
GO.transform.SetParent(parentObject);
AddProbability(_nextLevelID, probabilityToAdd);
// We change the references with the chunk just spawned
possibleLevels.Clear();
possibleLevels = new List<LevelID>(scriptableLevelChunk.InGamePossibleNeighbour);
}
private void AddProbability(LevelID _nextLevelID, float probabilityToAdd)
{
for(int i = 0;i<possibleLevels.Count;i++) {
if (possibleLevels[i] != _nextLevelID)
{
// This increases the probability for all the levels that are not picked
ResourceSystem.Instance.GetLevelChunk(possibleLevels[i]).Probability += probabilityToAdd;
}
else if (possibleLevels[i] == _nextLevelID)
{
// This resets the probability when we spawn a level
ScriptableLevelChunk thisLevel = ResourceSystem.Instance.GetLevelChunk(possibleLevels[i]);
thisLevel.Probability = thisLevel.InGameProbability;
}
}
}
public LevelID CreateChunk(Transform parentObject)
{
List<float> probabilities = GetProbabilityList(possibleLevels);
int index = GetWeightedRandomIndex(probabilities);
LevelID _levelID = possibleLevels[index];
CreateLevelChunk(_levelID, parentObject);
return _levelID;
}
}