今回やること
敵が移動する範囲の設定
NavMeshAgentの追加と設定
徘徊接近攻撃AIスクリプトの記述
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 |
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.AI;//NavMeshagentを使うために記述する public class Enemy : MonoBehaviour { public Vector3[] wayPoints = new Vector3[3];//徘徊するポイントの座標を代入するVector3型の変数を配列で作る private int currentRoot;//現在目指すポイントを代入する変数 private int Mode;//敵の行動パターンを分けるための変数 public Transform player;//プレイヤーの位置を取得するためのTransform型の変数 public Transform enemypos;//敵の位置を取得するためのTransform型の変数 private NavMeshAgent agent;//NavMeshAgentの情報を取得するためのNavmeshagent型の変数 void Start () { agent = GetComponent<NavMeshAgent> ();//NavMeshAgentの情報をagentに代入 } void Update () { Vector3 pos = wayPoints[currentRoot];//Vector3型のposに現在の目的地の座標を代入 float distance = Vector3.Distance(enemypos.position, player.transform.position);//敵とプレイヤーの距離を求める if (distance > 5) {//もしプレイヤーと敵の距離が5以上なら Mode = 0;//Modeを0にする } if (distance < 5) {//もしプレイヤーと敵の距離が5以下なら Mode = 1;//Modeを1にする } switch (Mode) {//Modeの切り替えは case 0://case0の場合 if (Vector3.Distance (transform.position, pos) < 1f) {//もし敵の位置と現在の目的地との距離が1以下なら currentRoot += 1;//currentRootを+1する if (currentRoot > wayPoints.Length -1) {//もしcurrentRootがwayPointsの要素数-1より大きいなら currentRoot = 0;//currentRootを0にする } } GetComponent<NavMeshAgent> ().SetDestination (pos);//NavMeshAgentの情報を取得し目的地をposにする break;//switch文の各パターンの最後につける case 1://case1の場合 agent.destination = player.transform.position;//プレイヤーに向かって進む break;//switch文の各パターンの最後につける } } } |
スクリプトの設定
①ここをおすと②③の設定が開く
②徘徊するポイントの数
③徘徊するポイントの座標
④プレイヤーと敵をそれぞれドラッグ&ドロップする
テストプレイをしてみると…
gifなのでカクついてるんですが実際はなめらかに動きます
[…] 敵AI(NavMeshAgent) […]