-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHealth.cs
More file actions
88 lines (79 loc) · 2.55 KB
/
Copy pathHealth.cs
File metadata and controls
88 lines (79 loc) · 2.55 KB
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
using System;
using UnityEngine;
public class Health: MonoBehaviour {
public event Action OnDamage;
public event Action OnDied;
static GameObject poofParticlesPrefab {
get {
if (_poofParticlesPrefab == null) {
_poofParticlesPrefab = Resources.Load<GameObject>("Poof-particles");
}
return _poofParticlesPrefab;
}
}
static GameObject _poofParticlesPrefab;
[SerializeField] EntityType entityType;
Collider hitbox;
Animator animator;
const string animDieTrigger = "Die";
public bool Dead { get; private set; }
const float invulnerableTime = 0.2f;
public float DeathDelay { get; set;} = 0.9f;
bool invulnerable = false;
AudioSource audioSource;
/// <summary>
/// SET ON AWAKE, ACCESS AT START OR LATER.
/// </summary>
public int HP {get ; private set;}
public void SetHealth(int health) {
HP = health;
}
void Awake() {
animator = GetComponent<Animator>();
if (TryGetComponent<AudioSource>(out var source)) {
audioSource = source;
} else {
audioSource = gameObject.AddComponent<AudioSource>();
}
hitbox = GetComponent<Collider>();
}
// Entrypoint for getting damaged
void OnTriggerEnter(Collider other) {
if (Dead) return;
if (other.TryGetComponent<Weapon>(out var weapon)) {
if (weapon.entityType != entityType)
Damage();
}
}
void Damage() {
if (Dead) return;
if (invulnerable) return;
if (entityType == EntityType.Player && Player.I.Dodging) return;
invulnerable = true;
new Timeout(() => invulnerable = false, invulnerableTime, this);
HP--;
OnDamage?.Invoke();
Sound.PlayClip(audioSource, SoundEffects.I.Damage);
if (HP <= 0) Die();
}
void Die() {
if (Dead) return;
OnDied?.Invoke();
if (hitbox != null) {
hitbox.enabled = false;
}
Dead = true;
animator.SetTrigger(animDieTrigger);
var poof = Instantiate(poofParticlesPrefab, transform.position, Quaternion.identity);
new Timeout(() => {
poof.GetComponent<ParticleSystem>().Play();
Destroy(poof, 1f);
}, DeathDelay);
if (entityType == EntityType.Enemy) {
Destroy(gameObject, DeathDelay);
}
if (entityType == EntityType.Player) {
new Timeout(() => Sound.PlayClipUniversal(SoundEffects.I.Defeat), 1f);
}
}
}