Skip to content

Instantly share code, notes, and snippets.

@tsubaki
Last active November 11, 2016 10:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tsubaki/5f09982229c4f316d7099a30c3de3fef to your computer and use it in GitHub Desktop.
Save tsubaki/5f09982229c4f316d7099a30c3de3fef to your computer and use it in GitHub Desktop.
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