2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

[Unity]一定距離になったら追ってくる機能の実装(Navmeshを使用)

Last updated at Posted at 2022-07-14

今回はあるオブジェクトの一定範囲にPlayerが入ったときに、そのオブジェクトが追いかけてくるという機能を作っていきます!

使用PC: MacBook Pro (13-inch, M1, 2020)
OSバージョン: 11.5.2
Unityバージョン:2021.3.2f1

今回使用したアセットは以下になります!参考にどうぞ😊

プレイヤー
エネミー
ステージ

実際にプレイすると

(動画ちょっとわかりづらくてごめんなさい)
基本は徘徊してて,,,
徘徊_1_AdobeExpress.gif

一定距離に近づくとプレイヤーに近づいてきて衝突したらゲームオーバーシーンに遷移する!
tuiseki.gif

目次

1.オブジェクトの準備
2.追跡・徘徊機能の構成
3.エネミーの設定
4.スクリプトの作成
5.徘徊用の目的地をランダムに生成する
6.最後の仕上げ!

オブジェクトの準備

今回は画像のようにオブジェクトを配置しました。
スクリーンショット 2022-07-12 11.27.32.png

プレイヤーはJoyStickで動くように事前に実装しました。
→やり方はこちら

エネミー本体とプレイヤーにCollider(種類はなんでも)RigidbodyをComponentとして付け加えておいてください!

追跡・徘徊機能の構成

今回は「一定距離に近づいたら」という処理を、当たり判定を使用してセンサーのように動かしていきたいと思います。
当たり判定が起動した場合に対象物を追跡し、起動していない場合はフィールドを自由徘徊する仕様にします。

追跡

センサー内にPlayerがいる場合、その範囲内でEnemyの方向をプレイヤーに向けさせ、そっちに進む感じです!

⏬イメージ図
スクリーンショット 2022-07-12 19.44.52.png

徘徊

逆にセンサー外にPlayerがいる時は、向かう目的地を一定時間おきにランダムでフィールド上に生成することによって自由徘徊をしているように見える実装をします。

⏬イメージ図
スクリーンショット 2022-07-12 17.11.09.png

エネミーの設定

センサーの設置

①HierarchyビューからCreateCreate Emptyで作成
スクリーンショット 2022-07-12 16.53.33.png

②Emptyオブジェクトの名前をsensorなどに変更し、Enemyの子オブジェクトにする。InspectorビューのAdd ComponentからBox Colliderを選択する。
スクリーンショット 2022-07-12 16.54.17.png

③Box ColliderのEdit Colliderのボタンをクリックして、Sceneビューの方でちょうど良い形にColliderの大きさを変更する。
スクリーンショット 2022-07-12 20.03.01.png

画像だとわかりづらいのですが、私はこんな感じの大きさにしました!薄ーい緑の線がColliderの大きさです。
スクリーンショット 2022-07-12 16.56.32.png

④Box Colliderのis Triggerにチェックを入れる。
スクリーンショット 2022-07-13 18.28.00.png

NavMeshの設定

①Enemy本体にInspectorビューのAdd ComponentからNav Mesh Agentを加える。
スクリーンショット 2022-07-12 20.12.42.png

②地面に当たるGameObjectのStaticをNavigation Staticにする
スクリーンショット 2022-07-13 17.59.08.png

(なければWindow→AI→Navigationを選択し、ウィンドウを表示する)
スクリーンショット 2022-07-13 18.02.23.png

③NavigationウィンドウのBakeタブの底のBakeボタンをクリックする。
スクリーンショット 2022-07-13 18.05.41.png
(右下のBake NavMeshが消えたら完了!少し時間がかかるかも,,,)

Bakeが終わったら青い移動できる範囲が示されます!
スクリーンショット 2022-07-13 18.20.26.png

エネミーのスクリプトの作成

ProjectビューからCreateC# ScriptEnemyScriptsensorScriptの二つを作成する。

エネミー本体のスクリプト

EnemyScriptに以下全文コピペ!

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.SceneManagement;

public class EnemyScript : MonoBehaviour
{
    public Transform Target;
    public Transform random;
    NavMeshAgent agent;
    bool sensor;
    public float speed;

    // Start is called before the first frame update
    void Start()
    {
        agent = GetComponent<NavMeshAgent>();
    }

    // Update is called once per frame
    void Update()
    {
        if(sensor == false)
        {
            agent.destination = random.transform.position;
        }
        else
        {
            agent.destination = Target.transform.position;
        }
    }

    public void tuiseki()
    {
        sensor = true;
    }

    public void haikai()
    {
        sensor = false;
    }

    private void OnCollisionEnter(Collision col)
    {
        if (col.gameObject.tag == "Player" )
        {
            SceneManager.LoadScene("GameOver");
        }
    }
}

センサー用のスクリプト

sensorScriptに以下全文コピペ!

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class sensorScript : MonoBehaviour
{
    public GameObject enemy;
    EnemyScript encs;

    // Start is called before the first frame update
    void Start()
    {
        encs = enemy.GetComponent<EnemyScript>();
    }

    void OnTriggerStay(Collider other)
    {
        if (other.gameObject.tag == "Player")
        {
            encs.tuiseki();
        }
    }

    void OnTriggerExit(Collider other)
    {
        if (other.gameObject.tag == "Player")
        {
            encs.haikai();
        }
    }
}

①それぞれにスクリプトをアタッチする
スクリーンショット 2022-07-13 18.10.14.png

②Enemyに必要なオブジェクトをアタッチして、Speedを好きな数字を入れる。
スクリーンショット 2022-07-13 18.23.09.png

③sensorにEnemyをアタッチする。
スクリーンショット 2022-07-13 18.24.51.png

徘徊用の目的地をランダムに生成する

①ランダムオブジェクトをHierarchyビューからCreateCreate Emptyで作成し、名前をrandomとかにする。
スクリーンショット 2022-07-13 12.32.57.png

②Projectビューから、ランダムオブジェクト用のスクリプトを作成する。
今回はコルーチンという機能を使って、ワープ処理を繰り返し行うように実装しました。

⏬スクリプト全文

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class randomScript : MonoBehaviour
{
    void Start()
    {
        StartCoroutine(Warp());
    }

    private IEnumerator Warp()
    {
        while (true)
        {
            // 10秒後ごとにワープ移動する。
            yield return new WaitForSeconds(10f);

            // ランダムな値を取得する。
            float posX = Random.Range(- 120, 120);
            float posZ = Random.Range(-200, 200);

            transform.position = new Vector3(posX, 0, posZ);
        }
    }
}

③スクリプトをHierarchtビューのRandomにアタッチする
スクリーンショット 2022-07-13 17.42.39.png

最後の仕上げ!

①PlayerにPlayerタグを追加する
スクリーンショット 2022-07-14 12.27.12.png

②ProjectビューからCreateSceneでGameOverのシーンを作成

FileBuild Settingsを開き、Scenes in Buildに遷移で使うシーンを入れる。
スクリーンショット 2022-07-14 11.24.36.png

以上!

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?