-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHealthSystem.cs
99 lines (81 loc) · 2.82 KB
/
HealthSystem.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
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
namespace RPG.Personagem
{
public class HealthSystem : MonoBehaviour
{
[SerializeField] float maxHealthPoints = 100f;
[SerializeField] Image healthBar;
[SerializeField] AudioClip[] damageSounds;
[SerializeField] AudioClip[] deathSounds;
[SerializeField] float deathVanishSecond = 4f;
const string DEATH_TRIGGER = "Death";
float currentHealthPoints;
Animator animator;
AudioSource audioSource;
Character characterMovement;
public float healthAsPercentage
{
get
{
return currentHealthPoints / maxHealthPoints;
}
}
void Start()
{
animator = GetComponent<Animator>();
audioSource = GetComponent<AudioSource>();
characterMovement = GetComponent<Character>();
currentHealthPoints = maxHealthPoints;
}
void Update()
{
UpdateHealthBar();
}
void UpdateHealthBar()
{
if (healthBar)
{
healthBar.fillAmount = healthAsPercentage;
}
}
public void TakeDamage(float damage)
{
bool characterDies = (currentHealthPoints - damage <= 0);
//mata player
currentHealthPoints = Mathf.Clamp(currentHealthPoints - damage, 0f, maxHealthPoints);
var clip = damageSounds[UnityEngine.Random.Range(0, damageSounds.Length)];
audioSource.PlayOneShot(clip);
if (characterDies)
{
StartCoroutine(KillCharacter());
}
}
public void Heal(float healpoints)
{
currentHealthPoints = Mathf.Clamp(currentHealthPoints + healpoints, 0f, maxHealthPoints);
}
IEnumerator KillCharacter()
{
characterMovement.Kill();
animator.SetTrigger(DEATH_TRIGGER);
var playerComponent = GetComponent<PlayerMovement>();
audioSource.clip = deathSounds[UnityEngine.Random.Range(0, deathSounds.Length)];
audioSource.Play();
if (playerComponent && playerComponent.isActiveAndEnabled)
{
print("GAME OVER");
yield return new WaitForSecondsRealtime(audioSource.clip.length + 3f); //use audioclip
SceneManager.LoadScene(0);
}
else
{
DestroyObject(gameObject, deathVanishSecond);
}
}
}
}