-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDrillCharacterController.cs
423 lines (383 loc) · 14.2 KB
/
DrillCharacterController.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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
using System;
using System.Collections;
using UnityEngine;
public class DrillCharacterController : PhysicsObject
{
// These are public to allow modification in unity.
#region gameplayvars
public float speed = 2f;
public float turnSpeed = 20f;
// Turn Radius is decreasing with velocity squared, with vel.sqrMag = upper maximally decreased and = lower minimally decreased
public float turnUpperSpeedBoundSqr = 7f*7f;
public float turnLowerSpeedBoundSqr = 1f;
// Acceleration
public float acc = 0.2f;
// Decceleration
public float brake = 0.1f;
// Threshold (squared) at which one deals more damage.
public float highSpeedThresholdSqr = 21f;
public float maxHealth = 4f;
#endregion
#region internalvars
bool debug = false;
// inputs are set via InputController/Command Pattern
public float input_turn { get; private set; }
float input_acc;
public Vector2 PositionOnSpawn {get; set;}
public int PlayerNumber {get; set;} = -1;
public int LivesLeft {get; set; }
/// <summary>
/// Indicates whether a drill is fast and should deal more damage.
/// </summary>
public bool highSpeed { get; private set; }
float currentHealth;
float timeUnderground;
float velocitySqrMagnitude;
Coroutine lastColliderTouchedCoroutine;
Collider2D lastColliderTouched;
/// <summary>
/// Number of rigidbodies staying inside this character.
/// </summary>
/// Used to check if a "new" collision takes place.
int triggerStaying;
bool invulnerable;
Renderer healthrenderer;
Color healthcolor;
ContactFilter2D contactFilter;
RaycastHit2D firstBodypartHit;
Renderer[] childRenderer;
ParticleSystem undergroundPS;
ParticleSystem hitEffect;
ParticleSystem drillsparksPS;
readonly float blinkTime = 0.1f;
readonly WaitForSeconds blinkWait = new WaitForSeconds(0.1f);
readonly WaitForSeconds invulnTime = new WaitForSeconds(1f);
readonly WaitForSeconds holdLastColliderTime = new WaitForSeconds(1f);
readonly Countdown countdown = new Countdown();
#endregion
#region coroutines
/// <summary>
/// Periodically disable renderer to make character blink.
/// </summary>
/// <param name="duration">Duration of the effect.</param>
IEnumerator DoBlinks(float duration)
{
while (duration > 0f) {
for (int i = 0; i < childRenderer.Length; i++)
childRenderer[i].enabled = !childRenderer[i].enabled;
duration -= blinkTime;
yield return blinkWait;
}
//make sure renderer is enabled when we exit
for (int i = 0; i < childRenderer.Length; i++)
childRenderer[i].enabled = true;
}
IEnumerator MakeInvulnerable()
{
invulnerable = true;
yield return invulnTime;
invulnerable = false;
}
/// <summary>
/// Freezes game for 20ms on hit. For extra juicyness.
/// </summary>
IEnumerator FreezeTimeOnHit()
{
Time.timeScale = 0f;
while(true)
{
float pauseEndTime = Time.realtimeSinceStartup + 0.02f;
while (Time.realtimeSinceStartup < pauseEndTime)
{
yield return 0;
}
break;
}
Time.timeScale = 1f;
}
/// <summary>
/// Disable game object after 100ms to allow scoring system to update.
/// TODO This is a bit hacky.
/// </summary>
IEnumerator DisableGameObject()
{
yield return blinkTime;
gameObject.SetActive(false);
}
/// <summary>
/// Hold the last collider that has hurt this character for a set amount of time
/// for scoring purposes.
/// </summary>
/// <param name="col">Other collider that has hurt this character.</param>
IEnumerator SetLastColliderTouched(Collider2D col)
{
lastColliderTouched = col;
yield return holdLastColliderTime;
lastColliderTouched = null;
}
#endregion
protected override void Awake()
{
if (PlayerNumber == -1)
throw new Exception("Set playerNumber before enabling. (Is the gameobject in the character prefab enabled which it shouldn't be?)");
base.Awake();
contactFilter.NoFilter();
childRenderer = transform.Find("hitbox").GetComponentsInChildren<Renderer>();
for (int i = 0; i < childRenderer.Length; i++)
childRenderer[i].material.color = GameManager.Instance.playerColors[PlayerNumber];
hitEffect = transform.Find("hit").GetComponent<ParticleSystem>();
drillsparksPS = transform.Find("drillsparks").GetComponent<ParticleSystem>();
drillsparksPS.Stop();
undergroundPS = transform.Find("underground particles").GetComponent<ParticleSystem>();
undergroundPS.Stop(withChildren:true);
healthcolor = new Color(255f,0f,0f,0f);
healthrenderer = transform.Find("_healthbar").gameObject.AddComponent<MeshRenderer>();
healthrenderer.material = new Material(Shader.Find("Transparent/VertexLit"));
healthrenderer.material.color = healthcolor;
healthrenderer.material.SetColor("_SpecColor", new Vector4(0f,0f,0f,0f));
Freeze();
}
/// <summary>
/// Resets the character to its spawn location/setup. Ends with player freezed.
/// </summary>
public override void Reset()
{
StopAllCoroutines();
base.Reset();
drillsparksPS.Stop();
undergroundPS.Stop(withChildren:true);
transform.position = PositionOnSpawn;
transform.rotation = Quaternion.identity;
currentHealth = maxHealth;
for (int i = 0; i < childRenderer.Length; i++)
childRenderer[i].enabled = true;
undergroundPS.Stop(withChildren:true);
if (healthrenderer != null)
{
healthcolor.a = 0f;
healthrenderer.material.color = healthcolor;
}
input_turn = 0f;
input_acc = 0f;
lastColliderTouchedCoroutine = null;
lastColliderTouched = null;
triggerStaying = 0;
invulnerable = false;
highSpeed = false;
Freeze();
}
/// <summary>
/// Resets the character to its spawn location/setup. Ends with countdown and a callback to begin playing.
/// </summary>
public void Respawn()
{
gameObject.SetActive(true);
Reset();
StartCoroutine(DoBlinks(0.5f));
StartCoroutine(MakeInvulnerable());
StartCoroutine(countdown.Start(0.5f, Unfreeze));
}
/// <summary>
/// Just used for debug mode.
/// </summary>
public void Update()
{
if(Input.GetKeyDown(KeyCode.P))
{
debug = !debug;
if(debug)
Time.timeScale = 0.1f;
else
{
Time.timeScale = 1f;
}
}
}
protected override void CustomMovement()
{
velocitySqrMagnitude = Velocity.sqrMagnitude;
// Rotate
AddTorque(
input_turn*turnSpeed*(
turnUpperSpeedBoundSqr-Mathf.Min(
Mathf.Max(velocitySqrMagnitude,turnLowerSpeedBoundSqr)-turnLowerSpeedBoundSqr,
turnUpperSpeedBoundSqr
)
)/turnUpperSpeedBoundSqr);
// Set highspeed
if(velocitySqrMagnitude > highSpeedThresholdSqr && Mathf.Sign(Vector2.Dot(Velocity,-transform.up)) == 1)
highSpeed = true;
else
highSpeed = false;
// If object has broken surface
if(underGround && transform.position.y > 0.5 * transform.localScale.y)
{
// Stop underground particles
undergroundPS.Stop(withChildren:true);
drillsparksPS.Clear();
drillsparksPS.Stop();
// Let physics engine handle the intrinsic velocity from here
// Thus we convert intrinsic to extrinsic and we return because
// no additional extrinsic forces will be applied in the air
AddForceRelToVel(intrinsicVelocity);
intrinsicVelocity = Vector2.zero;
timeUnderground = 0.0f;
return;
}
// If object is entering ground, play underground particles
if (!underGround && transform.position.y <= 0.5 * transform.localScale.y)
{
undergroundPS.Play(withChildren:true);
}
if(underGround)
{
if(highSpeed)
{
if(!drillsparksPS.IsAlive())
drillsparksPS.Play();
} else {
drillsparksPS.Stop();
}
timeUnderground += Time.fixedDeltaTime;
// Set underground forward motion as a mix of forces and intrinsic velocity
AddForceRelToVel(-transform.up*speed*0.12f);
intrinsicVelocity = -transform.up*speed*0.2f*Mathf.Min(timeUnderground,1f);
// Handle acceleration/braking
if (Mathf.Abs(input_acc) >= 0.01f)
{
if (input_acc > 0)
AddForceRelToVel(-transform.up*acc);
else
{
AddForceRelToVel(transform.up*brake);
}
}
}
}
/// <summary>
/// Check which rigidbody hit this character at which hitbox and act accordingly.
/// </summary>
/// <param name="other">Other collider that has hit this character.</param>
public void BodyPartHit(Collider2D other)
{
/// Only do this if there are not already other rigidbodies inside us.
/// This is done because we have two rigidbodies per character which could trigger this function
/// and we only want to execute this once.
if (triggerStaying == 0)
{
/// We determine which body part was hit first with a circlecast from the position of "other"
/// cast to our position
int hits = Physics2D.CircleCast(other.transform.position, 0.4f*transform.localScale.x, transform.position-other.transform.position, contactFilter, hitBuffer, 0.5f);
if(hits > 0)
{
// Get first body part hit
for (int i = 0; i < hits; i++)
{
if(hitBuffer[i].transform.CompareTag(transform.tag))
{
firstBodypartHit = hitBuffer[i];
break;
}
}
// Push us!
AddForce(5f*(transform.position-other.transform.position).normalized/Time.fixedDeltaTime);
// Set lastColliderTouched using a coroutine for scoring evaluation
if (lastColliderTouched) StopCoroutine(lastColliderTouchedCoroutine);
lastColliderTouchedCoroutine = StartCoroutine(SetLastColliderTouched(other));
// Deal damage!
// Calculation:
// body hit?
// Deal at least 1 damage
// Deal 1 additional damage if other.highSpeed
// drill hit?
// Deal 1 damage if other.highSpeed && !this.highSpeed
if(!invulnerable)
{
int additionalHighspeedDamage = other.GetComponent<DrillCharacterPart>().DrillController.highSpeed ? 1 : 0;
if(firstBodypartHit.transform.name == "body")
{
StartCoroutine(MakeInvulnerable());
Hurt(1 + additionalHighspeedDamage);
StartCoroutine(FreezeTimeOnHit());
}
else
{
if (additionalHighspeedDamage == 1 && !highSpeed)
{
StartCoroutine(MakeInvulnerable());
Hurt(1);
StartCoroutine(FreezeTimeOnHit());
}
}
}
}
}
}
/// <summary>Add 1 to triggerStaying counter.</summary>
public void TriggerEnter() { triggerStaying += 1; }
/// <summary>Subtract 1 from triggerStaying counter.</summary>
public void TriggerExit() { triggerStaying -= 1; }
/// <summary>
/// Damage health, update healthbar, play hit effect & report to scoring system.
/// </summary>
/// <param name="dmg">Damage dealt.</param>
public void Hurt(float dmg)
{
currentHealth = Mathf.Max(0f, currentHealth - dmg);
if (currentHealth <= 0f) {
LivesLeft -= 1;
for (int i = 0; i < childRenderer.Length; i++)
childRenderer[i].enabled = false;
StartCoroutine(DisableGameObject());
GameManager.Instance.LostLife(PlayerNumber, lastColliderTouched);
return;
}
else
hitEffect.Play();
if ((maxHealth-currentHealth)/maxHealth >= 0.5f)
healthcolor.a = (maxHealth-currentHealth)/maxHealth;
else
healthcolor.a = 0f;
healthrenderer.material.color = healthcolor;
StartCoroutine(DoBlinks(1f));
}
/// <summary>
/// Set tag of every child in hitbox. Useful when initializing characters at runtime.
/// </summary>
/// <param name="s"></param>
public void SetTag(string s)
{
transform.tag = s;
foreach (Transform child in transform.Find("hitbox"))
{
child.tag = s;
}
}
/// <summary>
/// Heal by amount and update healthbar.
/// </summary>
/// <param name="amount">Heal amount.</param>
public void Heal(float amount)
{
currentHealth = Mathf.Min(maxHealth, currentHealth + amount);
if ((maxHealth-currentHealth)/maxHealth >= 0.5f)
healthcolor.a = (maxHealth-currentHealth)/maxHealth;
else
healthcolor.a = 0f;
healthrenderer.material.color = healthcolor;
}
/// <summary>
/// Set input_turn; to be called from command.
/// </summary>
public void Turn(float f)
{
input_turn = f;
}
/// <summary>
/// Set input_accelerate; to be called from command.
/// </summary>
public void Accelerate(float f)
{
input_acc = f;
}
}