Random.Rangeで敵NPCの移動する目的地をランダムに設定するスクリプトを書いたのですが、動くNPCと動かないNPCがいます。NPCは10体、別のスクリプトで発生させています。
なぜか、スクリプトにある
x = Random.Range(0, 500);
z = Random.Range(0, 500);
を
x = Random.Range(0, 50);
z = Random.Range(0, 50);
に書き換えると全てのNPCが動きます。
理由が分かりません。
Terrain WidthとTerrain Lengthが500なので、Random.Rangeの最大値を500にしています。
さらに、NPCが目的地に到達すると、動きが止まってしまいます。
どのように直せばよいでしょうか?
回答よろしくお願いします。
C#
1using UnityEngine; 2using System.Collections; 3using UnityEngine.AI; 4 5 6public class AI : MonoBehaviour 7{ 8 9 public Transform target; //プレイヤーの位置 10 static Vector3 pos; 11 public NavMeshAgent agent; 12 13 float agentToPatroldistance; 14 float agentToTargetdistance; 15 16 GameObject EnemyAttack001; 17 HP hensuu; 18 bool yourVar; 19 bool isDamage = false; 20 public GameObject DamageImage001; 21 22 public AudioClip audioClip1; 23 private AudioSource audiosource; 24 25 public int x; 26 public int z; 27 28 IEnumerator InvincibleTime(float time) 29 { 30 isDamage = true; 31 yourVar = true; 32 yield return new WaitForSeconds(time); 33 isDamage = false; 34 } 35 36 void Awake() 37 { 38 agent = GetComponent<NavMeshAgent>(); 39 } 40 41 42 void Start() 43 { 44 DoPatrol(); 45 EnemyAttack001 = GameObject.Find("HPContorol"); 46 hensuu = EnemyAttack001.GetComponent<HP>(); 47 audiosource = gameObject.GetComponent<AudioSource>(); 48 audiosource.clip = audioClip1; 49 50 } 51 52 53 void Update() 54 { 55 //Agentと目的地の距離 56 agentToPatroldistance = Vector3.Distance(this.agent.transform.position, pos); 57 58 //Agentとプレイヤーの距離 59 agentToTargetdistance = Vector3.Distance(this.agent.transform.position, target.transform.position); 60 61 62 //プレイヤーとAgentの距離が30f以下になると追跡開始 63 if (agentToTargetdistance <= 30f) 64 { 65 DoTracking(); 66 67 68 //プレイヤーと目的地の距離が15f以下になると次の目的地をランダム指定 69 } 70 else if (agentToPatroldistance < 15f) 71 { 72 DoPatrol(); 73 74 } 75 76 77 78 } 79 80 81 82 //エージェントが向かう先をランダムに指定するメソッド 83 public void DoPatrol() 84 { 85 x = Random.Range(0, 500); 86 z = Random.Range(0, 500); 87 pos = new Vector3(x,0,z); 88 agent.SetDestination(pos); 89 agent.speed = 3.5f; 90 91 92 } 93 94 //targetに指定したplayerを追いかけるメソッド 95 public void DoTracking() 96 { 97 98 pos = target.position; 99 agent.SetDestination(pos); 100 101 102 103 } 104 105 private void OnTriggerEnter(Collider other) 106 { 107 if (!isDamage) 108 { 109 if (other.tag == "Player") 110 { 111 agent.speed = 0; 112 StartCoroutine("InvincibleTime", 3f); 113 StartCoroutine("DamageTime", 0.3f); 114 Invoke("DoPatrol", 1f); 115 if (yourVar) 116 { 117 hensuu.hp -= 20; 118 if (hensuu.hp <= 0) 119 { 120 hensuu.hp = 0; 121 } 122 } 123 } 124 } 125 126 } 127 128 IEnumerator DamageTime(float time) 129 { 130 DamageImage001.SetActive(true); 131 audiosource.Play(); 132 yield return new WaitForSeconds(time); 133 DamageImage001.SetActive(false); 134 } 135 136} 137 138 139
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。