#やりたいこと
Unityで2Dゲームを作っています。
NevMeshを使ってキャラクター(エージェント)を動かす際に、スプライトアニメーションを再生したいのですが、初回の移動だけうまくいきません。
#質問
NaMeshを使ってキャラクターを移動させた際、初回だけ、移動するのにNavMeshAgent.velocityが(0.0, 0.0, 0.0)になってしまいます。
2回目以降の移動では(1.0, 0.0, -0.2)という風に、値が入ってきます。
velocityだけではなくhasPathなども試してみたんですが、同様に初回だけfalseになってしまいます。
ちゃんと移動はしているのにパスがないって、どういうこと?って感じなのですが、こういうものなのでしょうか?
NavMeshを初めて使うので、何か変なところがないか見ていただけますでしょうか。
#該当するコード
キャラクターをドラッグして、MouseUpしたときにルート上なら、一旦ドラッグ開始地点に戻してから移動させてAnimatorを操作(Walk())します。
ドラッグ部分は問題ないので省略しています。当たり判定も問題ありません。
変数start_positionはドラッグ開始時のpositionを代入しています。
ドラッグしたキャラクターを最初の位置に戻すためです。
Characterクラス
cs
1 Animator animator; 2 NavMeshAgent agent; 3 Vector3 start_position; 4 5 void Update () 6 { 7 if (Input.GetMouseButtonUp (0)) { 8 OnStopDrag (); 9 } 10 } 11 12 void OnStopDrag () 13 { 14 Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition); 15 RaycastHit hit_info = new RaycastHit (); 16 float max_distance = 100f; 17 int layer = LayerMask.NameToLayer ("Route"); 18 int layer_mask = 1 << layer; 19 bool is_hit = Physics.Raycast (ray, out hit_info, max_distance, layer_mask); 20 21 transform.position = start_position; 22 if (is_hit) { 23 if (hit_info.transform.name.IndexOf ("DirectionChanger") != -1) { 24 //移動開始 25 agent.SetDestination (hit_info.point); 26 StartCoroutine (Walk ()); 27 } 28 } 29 } 30 31 IEnumerator Walk () 32 { 33 animator.SetBool ("attack", false); 34 animator.SetBool ("stop", false); 35 36 while (true) { 37 Debug.Log (agent.velocity); 38 39 if (agent.velocity.z > 0.5f) { 40 animator.SetInteger ("direction", 1); 41 } else if (agent.velocity.z < -0.5f) { 42 animator.SetInteger ("direction", 2); 43 } else if (agent.velocity.x > 0.5f) { 44 animator.SetInteger ("direction", 3); 45 } else if (agent.velocity.x < -0.5f) { 46 animator.SetInteger ("direction", 4); 47 } 48 now_direction = animator.GetInteger ("direction"); 49 50 if (agent.velocity == Vector3.zero) { 51 animator.SetBool ("stop", true); 52 yield break; 53 } 54 yield return null; 55 } 56 } 57
#出力結果
初回 (0.0, 0.0, 0.0)
Walkコルーチンはvelocityが0になったら抜けるようにしてあるので1度しか呼び出されません。
もちろん、アニメーションは変化しません。
移動はします。
2回目(1.0, 0.0, -0.2) ・・・・・ (0.0, 0.0, 0.0)
数値が変化しながら最後は0で終わります。
アニメーションも意図した通りに動いてくれています。
情報が不足していたら申し訳ございません。
よろしくお願いいたします。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/09/12 01:46 編集
2017/09/12 01:48
2017/09/12 02:07 編集
2017/09/12 02:13
2017/09/12 02:21
2017/09/12 02:33
2017/09/12 02:41