-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEnemyUnit.cs
More file actions
119 lines (105 loc) · 3.06 KB
/
EnemyUnit.cs
File metadata and controls
119 lines (105 loc) · 3.06 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
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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
using UnityEngine.AI;
public class EnemyUnit : MonoBehaviour {
public Camera cam;
public NavMeshAgent agent;
//public Transform target;
public GameObject target;
public Vector3 targetPos;
public float distanceFromPlayer;
public Image healthBar;
float speed = 3;
Vector3[] path;
int targetIndex;
public int maxHealth;
public int health;
void Start()
{
//PathRequestManager.RequestPath(transform.position, target.position, OnPathFound);
maxHealth = 100;
health = maxHealth;
}
void Update()
{
// if (Input.GetKeyDown(KeyCode.LeftControl)) {
// PathRequestManager.RequestPath(transform.position, target.position, OnPathFound);
// }
targetPos = target.transform.position;
distanceFromPlayer = Vector3.Distance(this.transform.position, targetPos);
//Go to Player when "E" is pressed
if(Input.GetKeyUp(KeyCode.E))
{
agent.SetDestination(targetPos);
}
//Go to point clicked on screen
if(Input.GetMouseButtonDown(0))
{
Ray ray = cam.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if(Physics.Raycast(ray, out hit))
{
agent.SetDestination(hit.point);
}
}
}
void TakeDamage(int damage)
{
// health -= damage;
// healthBar.fillAmount = (float)health / (float)maxHealth;
// if (health <= 0) {
// print ("dead");
// }
}
public void OnPathFound(Vector3[] newPath, bool pathSuccessful)
{
if (pathSuccessful)
{
path = newPath;
StopCoroutine("FollowPath");
StartCoroutine("FollowPath");
}
}
IEnumerator FollowPath()
{
Vector3 currentWaypoint = path[0];
while (true)
{
if (transform.position == currentWaypoint)
{
targetIndex++;
if (targetIndex >= path.Length)
{
print ("Movement DONE!");
targetIndex = 0;
path = new Vector3[0];
yield break;
}
currentWaypoint = path[targetIndex];
}
transform.position = Vector3.MoveTowards(transform.position, currentWaypoint, speed * Time.deltaTime);
yield return null;
}
}
public void OnDrawGizmos()
{
if (path != null)
{
for (int i = targetIndex; i < path.Length; i++)
{
Gizmos.color = Color.black;
Gizmos.DrawCube(path[i], Vector3.one * 0.3f);
if (i == targetIndex)
{
Gizmos.DrawLine(transform.position, path[i]);
}
else
{
Gizmos.DrawLine(path[i - 1], path[i]);
}
}
}
}
}