Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Navmeshの移動サンプル2
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class MoveTargetPosition : MonoBehaviour {
[SerializeField] NavMeshAgent agent = null;
Coroutine coroutine;
void OnEnable()
{
coroutine = StartCoroutine (UpdateNavmesh ());
}
void OnDisable()
{
StopCoroutine (coroutine);
}
// Navmesh移動のメインルーチン
IEnumerator UpdateNavmesh ()
{
var mainCamera = Camera.main;
var agentRigidbody = agent.GetComponent<Rigidbody> ();
RaycastHit hit = new RaycastHit();
NavMeshHit navHit = new NavMeshHit();
agentRigidbody.isKinematic = true;
while (true) {
// マウスを押すまで待機
// 場合によっては「キャラクターを選択するまで」に変更
// マウスを押したらNavmeshは停止
yield return new WaitWhile (() => Input.GetMouseButtonDown (0) == false);
agent.Stop ();
// マウスを上げるまで、マウスの位置とメッシュが交差する位置より2m高い位置にAgentを移動
// マウスを上げたら移動モードをRigidbodyに切替
yield return new WaitWhile (() => {
if (Physics.Raycast (mainCamera.ScreenPointToRay (Input.mousePosition).origin,
mainCamera.ScreenPointToRay (Input.mousePosition).direction, out hit, 100,
Physics.DefaultRaycastLayers)) {
agent.transform.localPosition = hit.point + Vector3.up * 2;
}
return Input.GetMouseButtonUp(0) == false;
});
agent.updatePosition = false;
agentRigidbody.isKinematic = false;
// Navmeshとの距離が0.1になるまで待つ
// 距離が詰まったら、移動モードをNavmeshに切替して、Navmeshの位置を直近のNavmeshに更新
yield return new WaitWhile(()=> NavMesh.SamplePosition (agent.transform.localPosition, out navHit, 0.1f, NavMesh.AllAreas) == false);
agent.Resume ();
agent.Warp (navHit.position);
agent.updatePosition = true;
agentRigidbody.isKinematic = true;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment