回答編集履歴
1
回答2を追加
answer
CHANGED
@@ -1,3 +1,4 @@
|
|
1
|
+
### 回答1
|
1
2
|
1つめのコード、以下のようにしてみてみたらどうでしょうか。
|
2
3
|
|
3
4
|
```C#
|
@@ -8,4 +9,55 @@
|
|
8
9
|
int y = Random.Range(4,104);
|
9
10
|
target.position = new Vecotor3(x,y,0);
|
10
11
|
}
|
12
|
+
```
|
13
|
+
|
14
|
+
### 回答2
|
15
|
+
全く別の物ですが、ランダムなターゲットに向かうスクリプトを書いてみました。ご参考まで。
|
16
|
+
[参考動画](https://twitter.com/onionslice2/status/997729377298268167)
|
17
|
+
```C#
|
18
|
+
using UnityEngine;
|
19
|
+
|
20
|
+
// Enemy オブジェクトにアタッチする
|
21
|
+
public class MoveToRandomTarget : MonoBehaviour
|
22
|
+
{
|
23
|
+
// シーン上に配置されているすべてのFoodオブジェクト
|
24
|
+
private GameObject[] foods;
|
25
|
+
|
26
|
+
// 向かう先
|
27
|
+
private Transform target;
|
28
|
+
|
29
|
+
private void Start ()
|
30
|
+
{
|
31
|
+
// シーン上の、"Food"タグの付けられたオブジェクトをすべて取得する
|
32
|
+
foods = GameObject.FindGameObjectsWithTag ( "Food" );
|
33
|
+
|
34
|
+
SelectRandomTarget ();
|
35
|
+
}
|
36
|
+
|
37
|
+
// ランダムにターゲットを選ぶ
|
38
|
+
private void SelectRandomTarget ()
|
39
|
+
{
|
40
|
+
target = foods[Random.Range ( 0, foods.Length )].transform;
|
41
|
+
}
|
42
|
+
|
43
|
+
|
44
|
+
// 以下は移動の例
|
45
|
+
|
46
|
+
private void FixedUpdate ()
|
47
|
+
{
|
48
|
+
GoToTarget ();
|
49
|
+
|
50
|
+
// 左クリックで新たなターゲットを選択
|
51
|
+
if ( Input.GetMouseButtonDown ( 0 ) )
|
52
|
+
{
|
53
|
+
SelectRandomTarget ();
|
54
|
+
}
|
55
|
+
}
|
56
|
+
|
57
|
+
private void GoToTarget ()
|
58
|
+
{
|
59
|
+
transform.position = Vector3.Lerp ( transform.position, target.position, 0.01f );
|
60
|
+
}
|
61
|
+
}
|
62
|
+
|
11
63
|
```
|