forked from ArztSamuel/Applying_EANNs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TrackManager.cs
318 lines (274 loc) · 10.1 KB
/
TrackManager.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
/// Author: Samuel Arzt
/// Date: March 2017
#region Includes
using System;
using UnityEngine;
using System.Collections.Generic;
#endregion
/// <summary>
/// Singleton class managing the current track and all cars racing on it, evaluating each individual.
/// </summary>
public class TrackManager : MonoBehaviour
{
#region Members
public static TrackManager Instance
{
get;
private set;
}
// Sprites for visualising best and second best cars. To be set in Unity Editor.
[SerializeField]
private Sprite BestCarSprite;
[SerializeField]
private Sprite SecondBestSprite;
[SerializeField]
private Sprite NormalCarSprite;
private Checkpoint[] checkpoints;
/// <summary>
/// Car used to create new cars and to set start position.
/// </summary>
public CarController PrototypeCar;
// Start position for cars
private Vector3 startPosition;
private Quaternion startRotation;
// Struct for storing the current cars and their position on the track.
private class RaceCar
{
public RaceCar(CarController car = null, uint checkpointIndex = 1)
{
this.Car = car;
this.CheckpointIndex = checkpointIndex;
}
public CarController Car;
public uint CheckpointIndex;
}
private List<RaceCar> cars = new List<RaceCar>();
/// <summary>
/// The amount of cars currently on the track.
/// </summary>
public int CarCount
{
get { return cars.Count; }
}
#region Best and Second best
private CarController bestCar = null;
/// <summary>
/// The current best car (furthest in the track).
/// </summary>
public CarController BestCar
{
get { return bestCar; }
private set
{
if (bestCar != value)
{
//Update appearance
if (BestCar != null)
BestCar.SpriteRenderer.sprite = NormalCarSprite;
if (value != null)
value.SpriteRenderer.sprite = BestCarSprite;
// best car is the car that is furthest in the track
// Debug.Log("Best car is: " + value.name);
value.TrailRenderer.time = 1000f;
//Set previous best to be second best now
CarController previousBest = bestCar;
bestCar = value;
if (BestCarChanged != null)
BestCarChanged(bestCar);
SecondBestCar = previousBest;
}
}
}
/// <summary>
/// Event for when the best car has changed.
/// </summary>
public event System.Action<CarController> BestCarChanged;
private CarController secondBestCar = null;
/// <summary>
/// The current second best car (furthest in the track).
/// </summary>
public CarController SecondBestCar
{
get { return secondBestCar; }
private set
{
if (SecondBestCar != value)
{
//Update appearance of car
if (SecondBestCar != null && SecondBestCar != BestCar)
SecondBestCar.SpriteRenderer.sprite = NormalCarSprite;
if (value != null)
value.SpriteRenderer.sprite = SecondBestSprite;
value.TrailRenderer.time = 100f;
secondBestCar = value;
if (SecondBestCarChanged != null)
SecondBestCarChanged(SecondBestCar);
}
}
}
/// <summary>
/// Event for when the second best car has changed.
/// </summary>
public event System.Action<CarController> SecondBestCarChanged;
#endregion
/// <summary>
/// The length of the current track in Unity units (accumulated distance between successive checkpoints).
/// </summary>
public float TrackLength
{
get;
private set;
}
#endregion
#region Constructors
void Awake()
{
// Set the time scale to 16x to speed up the simulation. This is not necessary, but makes it easier to see what is going on.
Time.timeScale = 32.0f;
// ZAMAN HIZLANDIRMA
if (Instance != null)
{
Debug.LogError("Mulitple instance of TrackManager are not allowed in one Scene.");
return;
}
Instance = this;
//Get all checkpoints
checkpoints = GetComponentsInChildren<Checkpoint>();
//Set start position and hide prototype
startPosition = PrototypeCar.transform.position;
startRotation = PrototypeCar.transform.rotation;
PrototypeCar.gameObject.SetActive(false);
CalculateCheckpointPercentages();
}
void Start()
{
//Hide checkpoints
foreach (Checkpoint check in checkpoints)
check.IsVisible = false;
}
#endregion
#region Methods
// Unity method for updating the simulation
void Update()
{
//Update reward for each enabled car on the track
for (int i = 0; i < cars.Count; i++)
{
RaceCar car = cars[i];
if (car.Car.enabled)
{
car.Car.CurrentCompletionReward = GetCompletePerc(car.Car, ref car.CheckpointIndex);
//Update best
if (BestCar == null || car.Car.CurrentCompletionReward >= BestCar.CurrentCompletionReward)
BestCar = car.Car;
else if (SecondBestCar == null || car.Car.CurrentCompletionReward >= SecondBestCar.CurrentCompletionReward)
SecondBestCar = car.Car;
}
}
}
public void SetCarAmount(int amount)
{
//Check arguments
if (amount < 0) throw new ArgumentException("Amount may not be less than zero.");
if (amount == CarCount) return;
if (amount > cars.Count)
{
//Add new cars
for (int toBeAdded = amount - cars.Count; toBeAdded > 0; toBeAdded--)
{
GameObject carCopy = Instantiate(PrototypeCar.gameObject);
carCopy.transform.position = startPosition;
carCopy.transform.rotation = startRotation;
CarController controllerCopy = carCopy.GetComponent<CarController>();
cars.Add(new RaceCar(controllerCopy, 1));
carCopy.SetActive(true);
}
}
else if (amount < cars.Count)
{
//Remove existing cars
for (int toBeRemoved = cars.Count - amount; toBeRemoved > 0; toBeRemoved--)
{
RaceCar last = cars[cars.Count - 1];
cars.RemoveAt(cars.Count - 1);
Destroy(last.Car.gameObject);
}
}
}
/// <summary>
/// Restarts all cars and puts them at the track start.
/// </summary>
public void Restart()
{
foreach (RaceCar car in cars)
{
car.Car.transform.position = startPosition;
car.Car.transform.rotation = startRotation;
car.Car.Restart();
car.CheckpointIndex = 1;
}
BestCar = null;
SecondBestCar = null;
}
/// <summary>
/// Returns an Enumerator for iterator through all cars currently on the track.
/// </summary>
public IEnumerator<CarController> GetCarEnumerator()
{
for (int i = 0; i < cars.Count; i++)
yield return cars[i].Car;
}
/// <summary>
/// gets MAX_DELTA_TIME from the car controller
/// </summary>
/// <returns></returns>
public float GetMaxDeltaTime()
{
return cars[0].Car.MAX_CHECKPOINT_DELAY;
}
/// <summary>
/// Calculates the percentage of the complete track a checkpoint accounts for. This method will
/// also refresh the <see cref="TrackLength"/> property.
/// </summary>
private void CalculateCheckpointPercentages()
{
checkpoints[0].AccumulatedDistance = 0; //First checkpoint is start
//Iterate over remaining checkpoints and set distance to previous and accumulated track distance.
for (int i = 1; i < checkpoints.Length; i++)
{
checkpoints[i].DistanceToPrevious = Vector2.Distance(checkpoints[i].transform.position, checkpoints[i - 1].transform.position);
checkpoints[i].AccumulatedDistance = checkpoints[i - 1].AccumulatedDistance + checkpoints[i].DistanceToPrevious;
}
//Set track length to accumulated distance of last checkpoint
TrackLength = checkpoints[checkpoints.Length - 1].AccumulatedDistance;
//Calculate reward value for each checkpoint
for (int i = 1; i < checkpoints.Length; i++)
{
checkpoints[i].RewardValue = (checkpoints[i].AccumulatedDistance / TrackLength) - checkpoints[i-1].AccumulatedReward;
checkpoints[i].AccumulatedReward = checkpoints[i - 1].AccumulatedReward + checkpoints[i].RewardValue;
}
}
// Calculates the completion percentage of given car with given completed last checkpoint.
// This method will update the given checkpoint index accordingly to the current position.
private float GetCompletePerc(CarController car, ref uint curCheckpointIndex)
{
//Already all checkpoints captured
if (curCheckpointIndex >= checkpoints.Length)
return 1;
//Calculate distance to next checkpoint
float checkPointDistance = Vector2.Distance(car.transform.position, checkpoints[curCheckpointIndex].transform.position);
//Check if checkpoint can be captured
if (checkPointDistance <= checkpoints[curCheckpointIndex].CaptureRadius)
{
curCheckpointIndex++;
car.CheckpointCaptured(); //Inform car that it captured a checkpoint
return GetCompletePerc(car, ref curCheckpointIndex); //Recursively check next checkpoint
}
else
{
//Return accumulated reward of last checkpoint + reward of distance to next checkpoint
return checkpoints[curCheckpointIndex - 1].AccumulatedReward + checkpoints[curCheckpointIndex].GetRewardValue(checkPointDistance);
}
}
#endregion
}