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
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PathfindingField : MonoBehaviour
{
[SerializeField] private Color defaultColor; // цвет клетки по умолчанию
[SerializeField] private Color pathColor; // подсветка пути
[SerializeField] private Color cursorColor; // подсветка указателя
[SerializeField] private LayerMask layerMask; // маска клетки
[SerializeField] private int width;
[SerializeField] private int height;
[SerializeField] [Range(1f, 10f)] private float moveSpeed = 1;
[SerializeField] [Range(0.1f, 1f)] private float rotationSpeed = 0.25f;
[SerializeField] private PathfindingNode[] grid;
private List<PathfindingNode> path;
private List<TargetPath> pathTarget;
private PathfindingNode start, end, last;
private Transform target;
private List<PathnodeParams> pathParams = new List<PathnodeParams>();
private int hash, index;
private bool move;
private PathfindingNode[,] map;
private static PathfindingField _inst;
public KeyCode moveLeft;
void Awake()
{
_inst = this;
BuildMap();
}
void BuildMap() // инициализация двумерного массива
{
map = new PathfindingNode[width, height];
int i = 0;
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
grid[i].x = x;
grid[i].y = y;
map[x, y] = grid[i];
i++;
}
}
UpdateNodeState_inst();
}
Vector3 NormalizeVector(Vector3 val) // округляем вектор до сотых
{
val.x = Mathf.Round(val.x * 100f) / 100f;
val.y = Mathf.Round(val.y * 100f) / 100f;
//val.z = Mathf.Round(val.z * 100f)/100f;
return val;
}
void BuildUnitPath() // создание точек движения и вектора вращения для юнита, на основе найденного пути
{
TargetPath p = new TargetPath();
pathTarget = new List<TargetPath>();
Vector3 directionLast = (path[0].transform.position - target.position).normalized;
p.direction = directionLast;
p.position = NormalizeVector(target.position);
pathTarget.Add(p);
//if(end.target != null) path.RemoveAt(path.Count-1);
for (int i = 0; i < path.Count; i++)
{
int id = (i + 1 < path.Count - 1) ? i + 1 : path.Count - 1;
Vector3 direction = (path[id].transform.position - path[i].transform.position).normalized;
if (direction != directionLast)
{
p = new TargetPath();
p.direction = (i < path.Count - 1) ? direction : directionLast;
p.position = NormalizeVector(path[i].transform.position);
pathTarget.Add(p);
}
directionLast = direction;
}
PathnodeParams pathParam = new PathnodeParams();
pathParam.pathTarget = pathTarget;
pathParam.start = start; //?
pathParam.end = end; //?
pathParam.last = last; //?
pathParam.target = target;
pathParams.Add(pathParam);
/*
* Сбрасываем все переменные, чтобы начать строить путь заново
* start = null
* end = null
* last = null
* target = null
* pathTarget = null
*/
}
void UpdateMove()
{
if (!move) return;
else if (index < pathTarget.Count - 1)
{
// анимация движения к следующей точке
target.position = Vector3.MoveTowards(target.position, pathTarget[index + 1].position, moveSpeed * Time.deltaTime);
if (Vector3.Distance(target.position, pathTarget[index + 1].position) < 0.1f)
{
target.position = pathTarget[index + 1].position;
index++;
}
}
else if (pathTarget.Count > 0 && index == pathTarget.Count - 1 && end.target != null && start.isPlayer)
{
// если юнита направили на другого юнита, когда он дойдет до него
TargetPath p = new TargetPath();
p.direction = (end.target.position - target.position).normalized;
p.position = target.position;
pathTarget.Add(p);
start.isPlayer = false;
index++;
}
else // если юнит достиг цели
{
UpdateNodeState_inst();
start.isPlayer = false;
start = null;
end = null;
hash = 0;
move = false;
}
}
void LateUpdate()
{
if (Input.GetKey(moveLeft))
{
UpdateMove();
}
if (move) return;
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit, Mathf.Infinity, layerMask))
{
PathfindingNode node = hit.transform.GetComponent<PathfindingNode>();
//if(node == null || node.isLock && node.target == null) return;
if (Input.GetMouseButtonDown(0))
{
if (node.target != null && end == null)
{
if (start != null) start.isPlayer = false;
start = node;
node.isPlayer = true;
node.cost = -1;
node.mesh.material.color = pathColor;
}
else if (end != null)
{
target = start.target;
BuildUnitPath();
index = 0;
move = true;
}
}
else if (Input.GetMouseButtonDown(1) && start != null)
{
start.isPlayer = false;
FieldUpdate();
start = null;
end = null;
hash = 0;
}
if (hash != node.GetInstanceID())
{
if (last != null && !last.isPlayer) last.mesh.material.color = defaultColor;
if (!node.isPlayer) node.mesh.material.color = cursorColor;
if (start != null && end != null)
{
FieldUpdate();
end = null;
}
if (start != null && node != null)
{
end = node;
path = Pathfinding.Find(start, node, map, width, height);
if (path == null)
{
FieldUpdate();
start = null;
end = null;
hash = 0;
return;
}
for (int i = 0; i < path.Count; i++)
{
path[i].mesh.material.color = pathColor;
}
}
}
last = node;
hash = node.GetInstanceID();
}
}
void UpdateNodeState_inst() // обновления поля, после совершения действия
{
for (int i = 0; i < grid.Length; i++)
{
RaycastHit hit; // пускаем луч сверху на клетку, проверяем занята она или нет
Physics.Raycast(grid[i].transform.position + Vector3.up * 100f, Vector3.down, out hit, 100f, ~layerMask);
if (hit.collider == null) // пустая клетка
{
grid[i].target = null;
grid[i].isLock = false;
grid[i].isPlayer = false;
grid[i].cost = -1; // свободное место
}
else if (hit.collider.tag == "Player") // найден юнит
{
grid[i].target = hit.transform;
grid[i].isLock = true;
grid[i].isPlayer = false;
grid[i].cost = -2; // препятствие
}
grid[i].mesh.material.color = defaultColor;
}
}
void FieldUpdate() // обновление поля, перед подсветкой пути
{
for (int i = 0; i < grid.Length; i++)
{
if (grid[i].isPlayer)
{
grid[i].cost = -1;
}
else if (grid[i].isLock)
{
grid[i].cost = -2;
grid[i].mesh.material.color = defaultColor;
}
else
{
grid[i].mesh.material.color = defaultColor;
grid[i].cost = -1;
}
}
}
#if UNITY_EDITOR
[SerializeField] private PathfindingNode sample; // шаблон клетки
[SerializeField] private float sampleSize = 1; // размер клетки
public void CreateGrid()
{
for (int i = 0; i < grid.Length; i++)
{
if (grid[i] != null) DestroyImmediate(grid[i].gameObject);
}
grid = new PathfindingNode[width * height];
float posX = -sampleSize * width / 2f - sampleSize / 2f;
float posY = sampleSize * height / 2f - sampleSize / 2f;
float Xreset = posX;
int z = 0;
for (int y = 0; y < height; y++)
{
posY -= sampleSize;
for (int x = 0; x < width; x++)
{
posX += sampleSize;
PathfindingNode clone = Instantiate(sample, new Vector3(posX, 0, posY), Quaternion.identity, transform) as PathfindingNode;
clone.transform.name = "Node-" + z;
grid[z] = clone;
z++;
}
posX = Xreset;
}
}
#endif
}
public struct TargetPath
{
public Vector3 direction, position;
}
public struct PathnodeParams
{
public List<PathfindingNode> path;
public List<TargetPath> pathTarget;
public Transform target;
public PathfindingNode start, end, last;
public int index;
} |