回答編集履歴

1

実装例を追記

2021/06/27 00:13

投稿

Bongo
Bongo

スコア10807

test CHANGED
@@ -4,39 +4,39 @@
4
4
 
5
5
  ```lang-csharp
6
6
 
7
- //始動したコルーチンを覚えておくためのフィールドを追加し...
7
+ //始動したコルーチンを覚えておくためのフィールドを追加し...
8
-
8
+
9
- private Coroutine movementAction;
9
+ private Coroutine movementAction;
10
-
11
-
12
-
10
+
11
+
12
+
13
- public void Start_MovementAction()
13
+ public void Start_MovementAction()
14
-
14
+
15
- {
15
+ {
16
-
16
+
17
- //コルーチン始動時にそれを保存
17
+ //コルーチン始動時にそれを保存
18
-
18
+
19
- movementAction = StartCoroutine(Move());
19
+ movementAction = StartCoroutine(Move());
20
-
20
+
21
- }
21
+ }
22
-
23
-
24
-
22
+
23
+
24
+
25
- //そして覚えておいたコルーチンを停止するためのメソッドを用意
25
+ //そして覚えておいたコルーチンを停止するためのメソッドを用意
26
-
26
+
27
- public void Stop_MovementAction()
27
+ public void Stop_MovementAction()
28
-
28
+
29
- {
29
+ {
30
-
30
+
31
- if (movementAction != null)
31
+ if (movementAction != null)
32
-
32
+
33
- {
33
+ {
34
-
34
+
35
- StopCoroutine(movementAction);
35
+ StopCoroutine(movementAction);
36
-
36
+
37
- }
37
+ }
38
-
38
+
39
- }
39
+ }
40
40
 
41
41
  ```
42
42
 
@@ -48,85 +48,85 @@
48
48
 
49
49
  ```lang-csharp
50
50
 
51
- //前回のUpdateで調べたターゲットの位置を保存するためのフィールドを追加
52
-
53
- private Vector2Int latestTargetPos;
54
-
55
-
56
-
57
- private void Update()
58
-
59
- {
60
-
61
- if(get_Distance)
62
-
63
- {
64
-
65
- float distanse = Vector2.Distance(gameObject.transform.position, selectedUnit.transform.position);
66
-
67
- if (distanse <= 3)
68
-
69
- {
70
-
71
- unit_RandomWalk_SelectedUnit.stoped_RandomWalk = true;
72
-
73
- int x = Mathf.RoundToInt(unit_RandomWalk_SelectedUnit.transform.position.x);
74
-
75
- int y = Mathf.RoundToInt(unit_RandomWalk_SelectedUnit.transform.position.y);
76
-
77
- unit_RandomWalk_SelectedUnit.transform.position = new Vector3(x, y, 0);
78
-
79
- }
80
-
81
- }
82
-
83
-
84
-
85
- //対象のユニットが存在していた座標に到達したら、ではなく...
86
-
87
- /*
88
-
89
- if (switched_Berserkermode && gameObject.transform.position == (Vector3)moving_From_PositionA_To_PositionB.moveList[moving_From_PositionA_To_PositionB.moveList.Count - 1])
90
-
91
- {
92
-
93
- Go_To_TargetUnit();
94
-
95
- }
96
-
97
- */
98
-
99
-
100
-
101
- if (switched_Berserkermode)
102
-
103
- {
104
-
105
- //現在のターゲットの位置を調べ...
106
-
107
- Vector2Int targetPos = new Vector2Int((int)selectedUnit.transform.position.x, (int)selectedUnit.transform.position.y);
108
-
109
-
110
-
111
- //敵の位置に変化があったら...
112
-
113
- if (targetPos != latestTargetPos)
114
-
115
- {
116
-
117
- //現在動作中の移動コルーチンは中止し、目的地への経路を再計算
118
-
119
- latestTargetPos = targetPos;
120
-
121
- moving_From_PositionA_To_PositionB.Stop_MovementAction();
122
-
123
- Go_To_TargetUnit();
124
-
125
- }
126
-
127
- }
128
-
129
- }
51
+ //前回のUpdateで調べたターゲットの位置を保存するためのフィールドを追加
52
+
53
+ private Vector2Int latestTargetPos;
54
+
55
+
56
+
57
+ private void Update()
58
+
59
+ {
60
+
61
+ if(get_Distance)
62
+
63
+ {
64
+
65
+ float distanse = Vector2.Distance(gameObject.transform.position, selectedUnit.transform.position);
66
+
67
+ if (distanse <= 3)
68
+
69
+ {
70
+
71
+ unit_RandomWalk_SelectedUnit.stoped_RandomWalk = true;
72
+
73
+ int x = Mathf.RoundToInt(unit_RandomWalk_SelectedUnit.transform.position.x);
74
+
75
+ int y = Mathf.RoundToInt(unit_RandomWalk_SelectedUnit.transform.position.y);
76
+
77
+ unit_RandomWalk_SelectedUnit.transform.position = new Vector3(x, y, 0);
78
+
79
+ }
80
+
81
+ }
82
+
83
+
84
+
85
+ //対象のユニットが存在していた座標に到達したら、ではなく...
86
+
87
+ /*
88
+
89
+ if (switched_Berserkermode && gameObject.transform.position == (Vector3)moving_From_PositionA_To_PositionB.moveList[moving_From_PositionA_To_PositionB.moveList.Count - 1])
90
+
91
+ {
92
+
93
+ Go_To_TargetUnit();
94
+
95
+ }
96
+
97
+ */
98
+
99
+
100
+
101
+ if (switched_Berserkermode)
102
+
103
+ {
104
+
105
+ //現在のターゲットの位置を調べ...
106
+
107
+ Vector2Int targetPos = new Vector2Int((int)selectedUnit.transform.position.x, (int)selectedUnit.transform.position.y);
108
+
109
+
110
+
111
+ //敵の位置に変化があったら...
112
+
113
+ if (targetPos != latestTargetPos)
114
+
115
+ {
116
+
117
+ //現在動作中の移動コルーチンは中止し、目的地への経路を再計算
118
+
119
+ latestTargetPos = targetPos;
120
+
121
+ moving_From_PositionA_To_PositionB.Stop_MovementAction();
122
+
123
+ Go_To_TargetUnit();
124
+
125
+ }
126
+
127
+ }
128
+
129
+ }
130
130
 
131
131
  ```
132
132
 
@@ -143,3 +143,547 @@
143
143
  何度も再計算するのは重そうに見えるかもしれませんが、経路がよっぽど長くなる...たとえば複雑な迷路状のマップで、ターゲットにたどり着くにはかなりの回り道をしなければいけない状況が頻発するとかでなければ、案外問題ないんじゃないかという気がします。
144
144
 
145
145
  これだと計算量が多すぎるようでしたら、「[Unity A*(A-Star)アルゴリズム 挙動がおかしくなる](https://teratail.com/questions/283731)」のコメントで申し上げたような、非同期化して他の処理へのインパクトを抑制するみたいな対策が必要かもしれませんね。
146
+
147
+
148
+
149
+ # 私の場合の実装例
150
+
151
+
152
+
153
+ まず、ご質問者さんの`Unit_RandomWalk`の代用品として下記のようなスクリプトを用意しました。これを各ユニットにアタッチして徘徊させます。
154
+
155
+
156
+
157
+ ```lang-csharp
158
+
159
+ using System.Collections;
160
+
161
+ using System.Collections.Generic;
162
+
163
+ using System.Linq;
164
+
165
+ using UnityEngine;
166
+
167
+
168
+
169
+ public class RandomWalk : MonoBehaviour
170
+
171
+ {
172
+
173
+ private static readonly Vector2[] Directions = {Vector2.up, Vector2.right, Vector2.down, Vector2.left};
174
+
175
+
176
+
177
+ [SerializeField][Min(0.0f)] private float idleDuration = 1.0f;
178
+
179
+ [SerializeField][Min(0.0f)] private float walkDuration = 0.5f;
180
+
181
+
182
+
183
+ private Coroutine randomWalkCoroutine;
184
+
185
+
186
+
187
+ private void Start()
188
+
189
+ {
190
+
191
+ Physics2D.queriesStartInColliders = false;
192
+
193
+ StartRandomWalk();
194
+
195
+ }
196
+
197
+
198
+
199
+ public void StartRandomWalk()
200
+
201
+ {
202
+
203
+ StopRandomWalk();
204
+
205
+ randomWalkCoroutine = StartCoroutine(RandomWalkLogic());
206
+
207
+ }
208
+
209
+
210
+
211
+ public void StopRandomWalk()
212
+
213
+ {
214
+
215
+ if (randomWalkCoroutine == null)
216
+
217
+ {
218
+
219
+ return;
220
+
221
+ }
222
+
223
+
224
+
225
+ StopCoroutine(randomWalkCoroutine);
226
+
227
+ randomWalkCoroutine = null;
228
+
229
+ }
230
+
231
+
232
+
233
+ private IEnumerator RandomWalkLogic()
234
+
235
+ {
236
+
237
+ WaitForSeconds wait = new WaitForSeconds(idleDuration);
238
+
239
+ List<Vector2> randomizedDirections = new List<Vector2>(4);
240
+
241
+ while (true)
242
+
243
+ {
244
+
245
+ yield return wait;
246
+
247
+
248
+
249
+ Vector2 currentPosition = this.transform.position;
250
+
251
+ randomizedDirections.Clear();
252
+
253
+ randomizedDirections.AddRange(Directions.Where(d => !Physics2D.Raycast(currentPosition, d, 1.0f)));
254
+
255
+ if (randomizedDirections.Count > 0)
256
+
257
+ {
258
+
259
+ Vector2 randomDirection = randomizedDirections[Random.Range(0, randomizedDirections.Count)];
260
+
261
+ Vector3 velocity = randomDirection / this.walkDuration;
262
+
263
+ float t = 0.0f;
264
+
265
+ while (true)
266
+
267
+ {
268
+
269
+ transform.Translate(velocity * Time.deltaTime);
270
+
271
+ t += Time.deltaTime;
272
+
273
+ if (t >= walkDuration)
274
+
275
+ {
276
+
277
+ break;
278
+
279
+ }
280
+
281
+ yield return null;
282
+
283
+ }
284
+
285
+ transform.position = currentPosition + randomDirection;
286
+
287
+ }
288
+
289
+ }
290
+
291
+ }
292
+
293
+ }
294
+
295
+ ```
296
+
297
+
298
+
299
+ そして`Moving_from_PositionA_to_PositionB`ですが、後述しますが`Berserkermode`側で移動動作を行わせようと思った都合から、下記のように変更を加えました。思考の整理上(そして字数の節約上)すみませんが大部分を削除してしまいましたので、必要な部分までなくなってしまっている可能性があります。あくまでも参考ということでご容赦ください。
300
+
301
+
302
+
303
+ ```lang-csharp
304
+
305
+ using System.Collections.ObjectModel;
306
+
307
+ using UnityEngine;
308
+
309
+
310
+
311
+ namespace UtilityModule
312
+
313
+ {
314
+
315
+ public class Moving_from_PositionA_to_PositionB : MonoBehaviour
316
+
317
+ {
318
+
319
+ private readonly int map_Height = 250;
320
+
321
+ private readonly int map_Width = 250;
322
+
323
+ private ChessboardPathFinder pathFinder;
324
+
325
+
326
+
327
+ public ReadOnlyCollection<Vector2Int> Path => pathFinder.Path;
328
+
329
+
330
+
331
+ private void Awake()
332
+
333
+ {
334
+
335
+ pathFinder = new ChessboardPathFinder(map_Width, map_Height);
336
+
337
+ }
338
+
339
+
340
+
341
+ public bool Find_Path(Vector2Int startPosition, Vector2Int goalPosition)
342
+
343
+ {
344
+
345
+ bool pathFound = pathFinder.FindPath(startPosition, goalPosition);
346
+
347
+ return pathFound;
348
+
349
+ }
350
+
351
+ }
352
+
353
+ }
354
+
355
+ ```
356
+
357
+
358
+
359
+ `Berserkermode`は下記のようにしました。これも同様にちょっと作りが変わってしまいましたので、参考として割り切っていただけるとありがたいです。
360
+
361
+
362
+
363
+ ```lang-csharp
364
+
365
+ using System.Collections;
366
+
367
+ using System.Linq;
368
+
369
+ using UnityEngine;
370
+
371
+ using UtilityModule;
372
+
373
+
374
+
375
+ namespace Module_of_Berserkermode
376
+
377
+ {
378
+
379
+ public class Berserkermode : MonoBehaviour
380
+
381
+ {
382
+
383
+ [SerializeField] private Material berserkerModeMaterial;
384
+
385
+ [SerializeField] private Material nonBerserkerModeMaterial;
386
+
387
+ [SerializeField][Min(0.0f)] private float walkDuration = 0.25f;
388
+
389
+
390
+
391
+ private Moving_from_PositionA_to_PositionB moving_From_PositionA_To_PositionB;
392
+
393
+ private Coroutine berserkerModeCoroutine;
394
+
395
+ private bool needsStopBerserkerMode;
396
+
397
+ private RandomWalk randomWalk;
398
+
399
+ private new Renderer renderer;
400
+
401
+
402
+
403
+ private bool IsBerserkerMode => berserkerModeCoroutine != null;
404
+
405
+
406
+
407
+ private void Awake()
408
+
409
+ {
410
+
411
+ moving_From_PositionA_To_PositionB = gameObject.GetComponent<Moving_from_PositionA_to_PositionB>();
412
+
413
+ randomWalk = GetComponent<RandomWalk>();
414
+
415
+ renderer = GetComponent<Renderer>();
416
+
417
+ }
418
+
419
+
420
+
421
+ private void Update()
422
+
423
+ {
424
+
425
+ // 実験目的ということで単純化し、不満値は設けずに
426
+
427
+ // スペースキーでバーサーカーモードを始動するようにした
428
+
429
+ if (Input.GetKeyDown(KeyCode.Space))
430
+
431
+ {
432
+
433
+ if (IsBerserkerMode)
434
+
435
+ {
436
+
437
+ StopBerserkerMode();
438
+
439
+ randomWalk.StartRandomWalk();
440
+
441
+ }
442
+
443
+ else
444
+
445
+ {
446
+
447
+ StartBerserkerMode();
448
+
449
+ }
450
+
451
+ }
452
+
453
+ }
454
+
455
+
456
+
457
+ private void StartBerserkerMode()
458
+
459
+ {
460
+
461
+ StopBerserkerMode();
462
+
463
+
464
+
465
+ // 視覚的にわかりやすくするため、バーサーカーモード用のマテリアル(赤色)に切り替える
466
+
467
+ renderer.material = berserkerModeMaterial;
468
+
469
+
470
+
471
+ // ランダム移動を停止、バーサーカーモードコルーチンを始動する
472
+
473
+ randomWalk.StopRandomWalk();
474
+
475
+ berserkerModeCoroutine = StartCoroutine(BerserkerModeLogic());
476
+
477
+ }
478
+
479
+
480
+
481
+ private void StopBerserkerMode()
482
+
483
+ {
484
+
485
+ if (berserkerModeCoroutine == null)
486
+
487
+ {
488
+
489
+ return;
490
+
491
+ }
492
+
493
+
494
+
495
+ // ユニットがタイル間を移動中の可能性があるので、次のタイルに到達するまでは待つことにする
496
+
497
+ StartCoroutine(WaitForStopBerserkerMode());
498
+
499
+ }
500
+
501
+
502
+
503
+ private IEnumerator WaitForStopBerserkerMode()
504
+
505
+ {
506
+
507
+ if (!IsBerserkerMode)
508
+
509
+ {
510
+
511
+ yield break;
512
+
513
+ }
514
+
515
+ needsStopBerserkerMode = true;
516
+
517
+ yield return berserkerModeCoroutine;
518
+
519
+ berserkerModeCoroutine = null;
520
+
521
+ needsStopBerserkerMode = false;
522
+
523
+
524
+
525
+ // 視覚的にわかりやすくするため、徘徊モード用のマテリアル(緑色)に切り替える
526
+
527
+ renderer.material = nonBerserkerModeMaterial;
528
+
529
+
530
+
531
+ // ランダム移動を再開
532
+
533
+ randomWalk.StartRandomWalk();
534
+
535
+ }
536
+
537
+
538
+
539
+ private IEnumerator BerserkerModeLogic()
540
+
541
+ {
542
+
543
+ while (true)
544
+
545
+ {
546
+
547
+ // まず、一番近いユニットをターゲットとして選択する
548
+
549
+ Transform targetTransform = GameObject.FindGameObjectsWithTag("Target")
550
+
551
+ .Select(target => (target.transform, Vector2.Distance(target.transform.position, transform.position)))
552
+
553
+ .OrderBy(pair => pair.Item2)
554
+
555
+ .Select(pair => pair.transform)
556
+
557
+ .FirstOrDefault();
558
+
559
+
560
+
561
+ // ターゲットの上下左右4タイルのうち、一番近いタイルを目的地として採用する
562
+
563
+ Vector2Int cellPosition = Vector2Int.RoundToInt(transform.position);
564
+
565
+ Vector2Int targetCellPosition = Vector2Int.RoundToInt(targetTransform.position);
566
+
567
+ Vector2Int destinationCellPosition = GetNearestNeighborCellPosition(cellPosition, targetCellPosition);
568
+
569
+
570
+
571
+ // パス探索を行う
572
+
573
+ // パスが見つからなかった場合はバーサーカーモードを終了する
574
+
575
+ if (!moving_From_PositionA_To_PositionB.Find_Path(cellPosition, destinationCellPosition) || (moving_From_PositionA_To_PositionB.Path.Count < 2))
576
+
577
+ {
578
+
579
+ break;
580
+
581
+ }
582
+
583
+
584
+
585
+ // 探索された経路を確認する目的で、シーンビュー上に黄色い線を引く
586
+
587
+ for (int i = 1; i < moving_From_PositionA_To_PositionB.Path.Count; i++)
588
+
589
+ {
590
+
591
+ Debug.DrawLine(
592
+
593
+ (Vector2)moving_From_PositionA_To_PositionB.Path[i],
594
+
595
+ (Vector2)moving_From_PositionA_To_PositionB.Path[i - 1],
596
+
597
+ Color.yellow);
598
+
599
+ }
600
+
601
+
602
+
603
+ // 経路上の次のタイルに向かって移動する
604
+
605
+ Vector3 nextTilePosition = (Vector3)(Vector2)moving_From_PositionA_To_PositionB.Path[1];
606
+
607
+ Vector3 velocity = (nextTilePosition - transform.position) / walkDuration;
608
+
609
+ float t = 0.0f;
610
+
611
+ while (true)
612
+
613
+ {
614
+
615
+ transform.Translate(velocity * Time.deltaTime);
616
+
617
+ t += Time.deltaTime;
618
+
619
+ if (t >= walkDuration)
620
+
621
+ {
622
+
623
+ break;
624
+
625
+ }
626
+
627
+ yield return null;
628
+
629
+ }
630
+
631
+ transform.position = nextTilePosition;
632
+
633
+
634
+
635
+ // バーサーカーモード終了要求が来ていたらループを終える
636
+
637
+ if (needsStopBerserkerMode)
638
+
639
+ {
640
+
641
+ break;
642
+
643
+ }
644
+
645
+ }
646
+
647
+ StopBerserkerMode();
648
+
649
+ }
650
+
651
+
652
+
653
+ private static Vector2Int GetNearestNeighborCellPosition(Vector2Int origin, Vector2Int target)
654
+
655
+ {
656
+
657
+ int deltaX = Mathf.Clamp(origin.x - target.x, -1, 1);
658
+
659
+ int deltaY = Mathf.Abs(deltaX) > 0 ? 0 : Mathf.Clamp(origin.y - target.y, -1, 1);
660
+
661
+ return new Vector2Int(target.x + deltaX, target.y + deltaY);
662
+
663
+ }
664
+
665
+ }
666
+
667
+ }
668
+
669
+ ```
670
+
671
+
672
+
673
+ 動きは下図のようになりました。
674
+
675
+
676
+
677
+ ![図1](dfa5c77c172ebf32668fa202de5b0a89.gif)
678
+
679
+
680
+
681
+ くの字の経路になってしまい、見苦しくてすみません。一応あれでもチェス盤空間においては最短経路の一つのはずですが、遠回りしているように感じます。「[Unity A*(A-Star)アルゴリズム 挙動がおかしくなる](https://teratail.com/questions/283731)」では、経路の評価に使う情報としては浮動小数点数の計算が必要なユークリッド距離よりも、チェス盤ならチェビシェフ距離を使って経路を評価した方がいいんじゃないかと思っていたのですが、こういった見苦しさにつながる可能性は失念していました。
682
+
683
+
684
+
685
+ ユークリッド距離を使うと縦横の経路の方が斜めの経路よりも高評価になりますので、下図のように見苦しさが低減するかと思います。こちらの方がお好みでしたら`ChessboardPathFinder`を適宜書き換えてしまってください。
686
+
687
+
688
+
689
+ ![図2](af6b81cef90c75200a118d76669e069c.gif)