プレイヤーを動かす(NavMesh)

歩ける範囲を設定して、キャラクタを歩かせよう

NavMeshを利用してキャラクターを移動させる方法です。

キャラクターの歩ける範囲NavMeshを設定(ベイク)して、その上を移動するキャラクターにNavMeshAgentをアタッチする必要があります。

キャラクターの歩く範囲を指定しよう

まずは足場となるオブジェクトを作成します。

次にそれを選択した状態で、インスペクタウィンドウのStaticにチェックを入れます。

次にメインメニューからWindow -> Navigationを撰択してナビゲーションのウィンドウを開き、 Bakeを押します。

これで歩ける範囲が指定できます。

地形によって、Agent Radiusなどを変更して歩ける範囲の設定を変更してみましょう。

キャラクターにNavMeshAgentをアタッチしよう

あとはキャラクターにNavMeshAgentをアタッチしましょう。 インスペクタウィンドウのAdd ComponentからNav Mesh Agentを追加します。

あとは目的地の座標をNavMeshAgentに渡すだけです。 クリックした位置に移動するには下記のように destination に値を渡して移動します。

using System.Collections;
using UnityEngine;
using UnityEngine.AI;

public class MoveNavMesh : MonoBehaviour {

	void Update () {
		//マウスをクリックしたら
		if(Input.GetMouseButtonUp(0)) {
			RaycastHit hit;

			//Rayを飛ばしてオブジェクトに当たったら
			if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit, 100)) {

				//NavMeshAgentを取得する
				NavMeshAgent agent = GetComponent<NavMeshAgent>();

				//当たった位置の座標を取得し、NavMeshAgentに渡す
				agent.destination = hit.point;
			}
		}
	}
}

キー操作に合わせて移動させる事も可能です。 カメラが固定の場合にはMoveに値を渡します。

カメラが固定の場合

Vector3 prev;
void Update () {
	//カメラが固定の場合の移動方法
	float moveHorizontal = Input.GetAxis ("Horizontal");
	float moveVertical = Input.GetAxis ("Vertical");
	agent.Move (new Vector3(moveHorizontal, 0, moveVertical));

	//進行方向に回転させる
	Vector3 diff = transform.position - prev;
	if (diff.magnitude > 0.01) {
		transform.rotation = Quaternion.LookRotation(diff);
	}
	prev = transform.position;
}

カメラが移動する場合

FPS視点やTPS視点など、画面に対してカメラの方向が変わる場合には下記のようにMoveさせる事でキャラクターを画面に対して正面に動かす事が可能です。

void Update () {
	float moveHorizontal = Input.GetAxis ("Horizontal");
	float moveVertical = Input.GetAxis ("Vertical");

	//キャラを回転させる
	transform.Rotate(new Vector3(0.0f, moveHorizontal, 0.0f));

	//キャラの向いている方向に移動
	agent.Move (transform.forward * moveVertical * 0.01f);
}